Answer the question
In order to leave comments, you need to log in
Validation in class template creation vector?
Task for the laboratory
Class name: Vector and overloaded operation << (collection output to the output stream). Something happened to me, but can you tell me what can be fixed or improved, or offer your own. And advise where to add work with exceptional situations.
#include <iostream>
#include <string.h>
#include <vector>
#include <typeinfo>
#include <bits/stream_iterator.h>
using namespace std;
template<class T>
class MainVector {
private:
T *m_ptv;
int m_size,
m_index;
public:
MainVector() : m_size(0), m_index(0), m_ptv(NULL) { }
MainVector(int);
~MainVector() {
delete[] m_ptv;
}
void addOneElem(const T &);
T *getVecor();
int getSizeVector();
};
template<class T>
T *MainVector<T>::getVecor() {
return m_ptv;
}
template<class T>
int MainVector<T>::getSizeVector() {
return m_size;
}
template<class T>
ostream &operator<<(ostream &stream, const vector<T> &values) {
stream << "[ ";
copy(begin(values), end(values), ostream_iterator<T>(stream, " "));
stream << ']';
return stream;
}
template<class T>
MainVector<T>::MainVector(int vectorSize) :
m_size(vectorSize), m_index(0) {
m_ptv = new T[m_size];
const type_info &t = typeid(T);
const char *azaz = t.name();
for (int i = 0; i < m_size; i++)
if (!strcmp(azaz, "char")) *(m_ptv + i) = ' ';
else *(m_ptv + i) = 0;
}
template<class T>
void MainVector<T>::addOneElem(const T &t) {
T *tmp = NULL;
if (++m_index >= m_size) {
tmp = m_ptv;
m_ptv = new T[m_size + 1];
}
if (tmp) memcpy(m_ptv, tmp, sizeof(T) * m_size);
m_ptv[m_size++] = t;
if (tmp)
delete[] tmp;
}
int main() {
cout << "Hello, Friday 13!" << endl;
vector<int> vectorOne;
vectorOne.push_back(5);
vectorOne.push_back(13);
vectorOne.push_back(666);
cout << "Vector #1 : [";
for (int i = 0; i < vectorOne.size(); ++i) {
cout << vectorOne[i] << ' ';
}
cout << "]";
cout << endl;
vector<char> vectorTwo;
vectorTwo.push_back('D');
vectorTwo.push_back('e');
vectorTwo.push_back('v');
vectorTwo.push_back('i');
vectorTwo.push_back('l');
cout << "Vector #2 : [";
for (int i = 0; i < vectorTwo.size(); ++i) {
cout << vectorTwo[i] << ' ';
}
cout << "]";
cout << endl;
cout << "Using overload ostream: " << endl;
cout << "Vector #1: " << vectorOne << " and Vector #2: " << vectorTwo;
return 0;
}
Answer the question
In order to leave comments, you need to log in
ostream &operator<<(ostream &stream, const vector<T> &values) {
template<class T>
ostream &operator<<(ostream &stream, const MainVector<T> &values) {
stream << "[ ";
copy(begin(values), end(values), ostream_iterator<T>(stream, " "));
stream << ']';
return stream;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question