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-07 10:48:54 浏览: 32
Certainly! Here's an example implementation of the `Vector` class template in C++:
```cpp
#include <iostream>
#include <vector>
template <typename T>
class Vector {
public:
Vector(std::size_t size) : data_(size) {}
T& operator[](std::size_t idx) {
return data_[idx];
}
const T& operator[](std::size_t idx) const {
return data_[idx];
}
friend std::istream& operator>>(std::istream& in, Vector<T>& v) {
for (std::size_t i = 0; i < v.size(); ++i) {
in >> v[i];
}
return in;
}
friend std::ostream& operator<<(std::ostream& out, const Vector<T>& v) {
out << "[ ";
for (std::size_t i = 0; i < v.size(); ++i) {
out << v[i] << " ";
}
out << "]";
return out;
}
std::size_t size() const {
return data_.size();
}
private:
std::vector<T> data_;
};
```
This implementation defines a `Vector` class template that takes a single template parameter `T` representing the element type of the vector. The class contains a constructor that takes a `std::size_t` parameter representing the size of the vector, and a subscript operator `operator[]` that allows access to individual elements of the vector.
The class also defines two friend functions `operator>>` and `operator<<` for input and output, respectively. These functions allow vectors to be streamed to and from `std::istream` and `std::ostream` objects, making it easy to read and write vectors to files or the console.
Finally, the class provides a `size()` function that returns the size of the vector.
Here's an example of how you could use this class to create and manipulate a vector of `int` elements:
```cpp
int main() {
Vector<int> v(5); // Create a vector of 5 ints
std::cin >> v; // Read values into the vector
std::cout << v; // Print the vector
return 0;
}
```
In this example, the program creates a `Vector` object `v` containing 5 `int` elements, reads values into the vector using the overloaded `operator>>`, and then prints the vector to the console using the overloaded `operator<<`.
阅读全文