gpt4 book ai didi

c++ - C++过滤掉数组中的重复值

转载 作者:行者123 更新时间:2023-11-30 05:07:24 26 4
gpt4 key购买 nike

例如,我有一排十个数字:

5 5 6 7 5 9 4 2 2 7

现在我想要一个程序来找到所有重复项并在控制台中给出它们,例如 3 乘以 5、2 乘以 2、2 乘以 7。虽然我确实编写了一个算法来查找一行数字中的重复项,但我无法按照描述在控制台中给出它们。我的程序将输出:

3 times 5
2 times 5
2 times 7
2 times 2

我该如何解决这个问题?

#include <iostream>

using namespace std;

int main()
{
int arr[10];
int i,j;
int z = 1;

for(i = 0; i < 10; i++) {
cin >> arr[i];
}
for(i = 0; i < 10; i++){
for(j = i+1; j < 10; j++){
if(arr[i] == arr[j]){
z++;
}
}
if(z >= 2){
cout << z << " times " << arr[i] << endl;
z = 1;
}

}


return 0;
}

最佳答案

您可以在此处使用 STL (C++11):

int arr[10];
std::map<int, int> counters;

for (auto item : arr)
{
cin >> item;
++counters[item];
}

std::for_each(counters.begin(), counters.end(), [](const std::pair<int,int>& item)
{
if(item.second > 1) std::cout << item.second << " times " << item.first << std::endl;
});

关于c++ - C++过滤掉数组中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47469728/

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