Define a class template called Vector(a single-column- Matrix). The templates can instantiate a vector of any element type. Overloaded >> and << operators: to enable input and output of a vector, respectively
时间: 2023-07-16 20:16:58 浏览: 93
Here is an implementation of the Vector class template with overloaded >> and << operators:
```c++
#include <iostream>
#include <vector>
template <typename T>
class Vector {
private:
std::vector<T> data;
public:
Vector() {}
Vector(std::initializer_list<T> list) : data(list) {}
// Overloading << operator
friend std::ostream& operator<<(std::ostream& os, const Vector<T>& vec) {
os << "[ ";
for (const auto& element : vec.data) {
os << element << " ";
}
os << "]";
return os;
}
// Overloading >> operator
friend std::istream& operator>>(std::istream& is, Vector<T>& vec) {
T element;
while (is >> element) {
vec.data.push_back(element);
}
return is;
}
};
int main() {
Vector<int> vec1{1, 2, 3, 4, 5};
std::cout << vec1 << std::endl; // Output: [ 1 2 3 4 5 ]
Vector<double> vec2;
std::cout << "Enter vector elements: ";
std::cin >> vec2;
std::cout << "Vector entered: " << vec2 << std::endl;
return 0;
}
```
In this implementation, the Vector class template is defined with a private member variable `data` of type `std::vector<T>`. The overloaded << operator prints out the elements of the vector in the format `[ element1 element2 ... elementN ]`, and the overloaded >> operator reads in elements from the input stream and appends them to the vector.
In the main function, we create two instances of the Vector class template, one with an initializer list and one with user input. We print out the first vector using the overloaded << operator, and then prompt the user to enter elements for the second vector using the overloaded >> operator. Finally, we print out the second vector using the overloaded << operator.
阅读全文