gpt4 book ai didi

c++ - C++中的不同数字

转载 作者:行者123 更新时间:2023-11-28 00:24:49 25 4
gpt4 key购买 nike

首先我想说我是编程新手。我在用 C++ 编写来自另一个列表的不同数字列表时遇到问题。假设我有一个列表 l1 = {1, 12, 2, 4, 1, 3, 2} 我想创建一个看起来像这样的新列表 l2 = {1, 12, 2, 4, 3}...

这是我写的:

#include <iostream>

using namespace std;

int main() {
int l1[100], l2[100], length, length1 = 0, i, j, a = 0;
cin >> length; //set the length
for (i = 0; i < length; i++) {
cin >> l1[i]; //add numbers to the list
}
l2[0] = l1[0]; //added the first number manually
for (i = 0; i < length; i++) {
length1++;
a = 0;
for (j = 0; j < length1; j++) {
if (l1[i] != l2[j]) //this checks numbers in the second list
a = 1; // and if they aren't found a gets the value
} //1 so after it's done checking if a is 1 it
if (a == 1) //will add the number to the list, but if the
l2[j] = l1[i]; //number is found then a is 0 and nothing happens,
} // SUPPOSEDLY
for (j = 0; j < length1; j++) {
cout << l2[j] << " ";
}
}

它的输出是 1 -858993460 12 2 4 1 3 所以显然我做错了什么。我欢迎您提出任何建议,我不一定需要解决方案,我只是想摆脱困境。非常感谢您花时间回复此问题。

最佳答案

std::sort(l1, l1 + 100);
int* end_uniques = std::unique(l1, l1 + 100);
std::copy(l1, end_uniques, l2);
size_t num_uniques = end_uniques - l1;

这是 O(N log N) 而不是 O(N^2) 的解决方案,因此理论上更快。它需要首先对数组 l1 进行排序(就地)以让 std::unique 工作。然后你得到一个指向唯一元素末尾的指针,你可以使用它复制到 l2 并且当然得到计数(因为它当然可能小于 100 的完整大小)。

关于c++ - C++中的不同数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25587998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com