用C++代码实现能够人工输入或随机产生一个长度为n的整数数组,要求数组任意两个元素都互不相同;
时间: 2024-05-13 12:18:07 浏览: 8
可以使用C++的STL库中的set容器来实现,以下是示例代码:
```c++
#include <iostream>
#include <set>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
int n;
cout << "请输入数组长度n:";
cin >> n;
// 使用set容器来存储元素,保证元素不重复
set<int> s;
// 随机产生n个不重复的元素
srand(time(NULL));
while (s.size() < n) {
s.insert(rand() % 1000); // 生成0~999的随机数
}
// 将set容器中的元素复制到数组中
int arr[n], i = 0;
for (auto it = s.begin(); it != s.end(); it++) {
arr[i++] = *it;
}
// 输出数组
cout << "生成的数组为:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
运行结果示例:
```
请输入数组长度n:10
生成的数组为:7 19 37 205 210 326 406 617 698 937
```