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.
时间: 2024-03-03 15:51:30 浏览: 58
Sure, here's an implementation of the Vector class template in C++:
```cpp
#include <iostream>
#include <vector>
template <typename T>
class Vector {
public:
Vector() {}
Vector(std::size_t size) : data_(size) {}
std::size_t size() const { return data_.size(); }
T& operator[](std::size_t index) { return data_[index]; }
const T& operator[](std::size_t index) const { return data_[index]; }
friend std::ostream& operator<<(std::ostream& os, const Vector<T>& vec) {
for (std::size_t i = 0; i < vec.size(); ++i) {
os << vec[i] << " ";
}
return os;
}
friend std::istream& operator>>(std::istream& is, Vector<T>& vec) {
std::size_t size;
is >> size;
vec = Vector<T>(size);
for (std::size_t i = 0; i < size; ++i) {
is >> vec[i];
}
return is;
}
private:
std::vector<T> data_;
};
```
The `Vector` class template can be instantiated with any element type. It has a default constructor and a constructor that takes a size argument to create a vector of a specific size. The `size()` method returns the size of the vector.
The `operator[]` method is overloaded to allow indexing of the vector. The `friend` keyword is used to declare the `operator<<` and `operator>>` functions as friend functions that can access the private `data_` member of the `Vector` class.
The `operator<<` function outputs the elements of the vector to the output stream, separated by spaces. The `operator>>` function reads in the size of the vector from the input stream, creates a new `Vector` of that size, and reads in the elements of the vector from the input stream.
Example usage:
```cpp
int main() {
Vector<int> vec(3);
std::cin >> vec;
std::cout << vec << std::endl;
return 0;
}
```
This program creates a `Vector` of size 3, reads in 3 integers from the input stream to fill the vector, and then outputs the vector to the output stream.
阅读全文