C++定义一个复数类,随机生成一个无序的复数向量(有重复项) (1)在主函数中测试无序向量的置乱、查找(实部和虚部均相同)、插入、删除和唯一化的操作
时间: 2024-06-01 08:10:25 浏览: 192
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
class Complex {
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
double real; // 实部
double imag; // 虚部
bool operator==(const Complex& c) const {
return (real == c.real) && (imag == c.imag);
}
};
// 打乱向量顺序
void shuffle(vector<Complex>& v) {
srand(time(NULL)); // 用时间作为随机种子
for (int i = v.size() - 1; i > 0; --i) {
int j = rand() % (i + 1);
swap(v[i], v[j]);
}
}
// 查找复数在向量中的位置
int find(const vector<Complex>& v, const Complex& c) {
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] == c) {
return i;
}
}
return -1;
}
// 插入复数到向量中
void insert(vector<Complex>& v, const Complex& c) {
v.push_back(c);
}
// 删除指定位置的复数
void remove(vector<Complex>& v, int index) {
v.erase(v.begin() + index);
}
// 唯一化向量,去掉重复项
void unique(vector<Complex>& v) {
vector<Complex> tmp;
for (size_t i = 0; i < v.size(); ++i) {
if (find(tmp, v[i]) == -1) {
tmp.push_back(v[i]);
}
}
v = tmp;
}
int main() {
vector<Complex> v;
v.push_back(Complex(1, 2));
v.push_back(Complex(3, 4));
v.push_back(Complex(1, 2));
v.push_back(Complex(5, 6));
v.push_back(Complex(7, 8));
v.push_back(Complex(3, 4));
cout << "Original vector:" << endl;
for (size_t i = 0; i < v.size(); ++i) {
cout << v[i].real << "+" << v[i].imag << "i" << endl;
}
shuffle(v);
cout << "\nShuffled vector:" << endl;
for (size_t i = 0; i < v.size(); ++i) {
cout << v[i].real << "+" << v[i].imag << "i" << endl;
}
Complex c(7, 8);
int index = find(v, c);
if (index != -1) {
cout << "\nFound " << c.real << "+" << c.imag << "i at index " << index << endl;
} else {
cout << "\n" << c.real << "+" << c.imag << "i not found" << endl;
}
c = Complex(3, 4);
index = find(v, c);
if (index != -1) {
cout << "\nFound " << c.real << "+" << c.imag << "i at index " << index << endl;
} else {
cout << "\n" << c.real << "+" << c.imag << "i not found" << endl;
}
c = Complex(9, 10);
insert(v, c);
cout << "\nAfter inserting " << c.real << "+" << c.imag << "i:" << endl;
for (size_t i = 0; i < v.size(); ++i) {
cout << v[i].real << "+" << v[i].imag << "i" << endl;
}
index = 2;
remove(v, index);
cout << "\nAfter removing element at index " << index << ":" << endl;
for (size_t i = 0; i < v.size(); ++i) {
cout << v[i].real << "+" << v[i].imag << "i" << endl;
}
unique(v);
cout << "\nAfter unique:" << endl;
for (size_t i = 0; i < v.size(); ++i) {
cout << v[i].real << "+" << v[i].imag << "i" << endl;
}
return 0;
}
阅读全文