在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
可能更簡單且易于理解。選擇最適合您需求的方法。