在C++中,可以使用多种方法来查找重复元素
std::set
:#include<iostream>
#include<vector>
#include <set>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1};
std::set<int> unique_numbers;
for (int number : numbers) {
if (unique_numbers.find(number) != unique_numbers.end()) {
std::cout << "Repeated element: "<< number<< std::endl;
} else {
unique_numbers.insert(number);
}
}
return 0;
}
std::unordered_set
:#include<iostream>
#include<vector>
#include <unordered_set>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1};
std::unordered_set<int> unique_numbers;
for (int number : numbers) {
if (unique_numbers.find(number) != unique_numbers.end()) {
std::cout << "Repeated element: "<< number<< std::endl;
} else {
unique_numbers.insert(number);
}
}
return 0;
}
std::count
:#include<iostream>
#include<vector>
#include<algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1};
for (int number : numbers) {
if (std::count(numbers.begin(), numbers.end(), number) > 1) {
std::cout << "Repeated element: "<< number<< std::endl;
}
}
return 0;
}
请注意,这些方法在不同情况下可能有不同的性能。例如,使用std::set
或std::unordered_set
通常比使用std::count
更高效,特别是在大型数据集中。然而,在某些情况下,std::count
可能更简单且易于理解。选择最适合您需求的方法。