利用c++编写下列程序,假设有向量X=(x1, x2,…, xn)和Y=(y1, y2,…, yn) 它们之间的加、减和乘法分别定义为 X + Y = (x1 + y1, x2 + y2,…, xn + yn) X - Y = (x1 - y1, x2 - y2,…, xn - yn) X * Y = x1 * y1 + x2 * y2 +…+ xn * yn 编写程序定义向量类Vector, 重载运算符+、-、*和=, 实现向量之间的加、减、乘、赋值运算; 重载运算符>>、<<实现向量的输入、输出功能
时间: 2023-06-09 20:02:58 浏览: 211
c++实现向量运算.7z
5星 · 资源好评率100%
以下是向量类Vector的实现代码:
#include <iostream>
#include <vector>
using namespace std;
class Vector {
private:
vector<double> v;
public:
Vector(int n) {
v.resize(n, 0);
}
int length() const {
return v.size();
}
double& operator[](int i) {
return v[i];
}
const double& operator[](int i) const {
return v[i];
}
Vector operator+(const Vector& other) const {
Vector result(length());
for (int i = 0; i < length(); i++) {
result[i] = v[i] + other[i];
}
return result;
}
Vector operator-(const Vector& other) const {
Vector result(length());
for (int i = 0; i < length(); i++) {
result[i] = v[i] - other[i];
}
return result;
}
double operator*(const Vector& other) const {
double result = 0;
for (int i = 0; i < length(); i++) {
result += v[i] * other[i];
}
return result;
}
Vector& operator=(const Vector& other) {
if (this != &other) {
v = other.v;
}
return *this;
}
friend istream& operator>>(istream& in, Vector& vec) {
int n = vec.length();
for (int i = 0; i < n; i++) {
in >> vec[i];
}
return in;
}
friend ostream& operator<<(ostream& out, const Vector& vec) {
out << '(';
int n = vec.length();
for (int i = 0; i < n; i++) {
out << vec[i];
if (i < n - 1) {
out << ", ";
}
}
out << ')';
return out;
}
};
下面是一些测试函数:
void test_add() {
Vector a(3);
a[0] = 1;
a[1] = 2;
a[2] = 3;
Vector b(3);
b[0] = 4;
b[1] = 5;
b[2] = 6;
Vector c = a + b;
cout << c << endl; // expected output: (5, 7, 9)
}
void test_sub() {
Vector a(3);
a[0] = 1;
a[1] = 2;
a[2] = 3;
Vector b(3);
b[0] = 4;
b[1] = 5;
b[2] = 6;
Vector c = a - b;
cout << c << endl; // expected output: (-3, -3, -3)
}
void test_dot() {
Vector a(3);
a[0] = 1;
a[1] = 2;
a[2] = 3;
Vector b(3);
b[0] = 4;
b[1] = 5;
b[2] = 6;
double c = a * b;
cout << c << endl; // expected output: 32
}
void test_io() {
Vector vec(3);
cout << "Please input a vector of length 3:" << endl;
cin >> vec;
cout << "The input vector is: " << vec << endl;
}
int main() {
test_add();
test_sub();
test_dot();
test_io();
return 0;
}
阅读全文