您可以使用std::set
, std::set_difference
,std::sort
来查找最低重复元素:
#include <vector>
#include <set>
#include <iostream>
int main() {
int gpas[] = {100,30,97,67,89,100,90,67,100,67,30,1,1};//sample values
std::vector<int> vec(gpas, gpas + sizeof(gpas)/sizeof(int));//this constructor is only valid for stack allocated arrays
std::set<int> cpy(vec.begin(), vec.end());//create a set with the unique gpas in a set
std::vector<int> duplicates;
std::set<int>::const_iterator it;
std::sort(vec.begin(), vec.end());//sort the set as set_difference requires that the container is sorted
//find the duplicates using set_difference. This will find all duplicates
//(which will be repeated n - 1 times in `duplicates` for n > 1)
std::set_difference(vec.begin(), vec.end(), cpy.begin(), cpy.end(), std::back_inserter(duplicates));
//this creates a set from all the duplicates found
std::set<int> unique_duplicates(duplicates.begin(), duplicates.end());
//output the duplicates
for (it = unique_duplicates.begin(); it != unique_duplicates.end(); ++it) {
std::cout << *it << std::endl;
}
//if you want the lowest value of the duplicates:
//you can use the min_element from <algorithm>:
//std::min_element(unique_duplicates.begin(), unique_duplicates.end());
//However, as the vector `vec` was already sorted, this ensures that
//all the other results obtained from the sorted vector will ALREADY
//be sorted. Hence, if size is > 0, then we can simply look at the
//first element alone.
if (unique_duplicates.size() > 0) {
it = unique_duplicates.begin();
std::cout << "The LOWEST duplicate element is: " << *it << std::endl;
}
return 0;
}
从发布的示例数据中,输出:
1
30
67
100
作为重复元素
并且,1
作为最低重复元素。
参考:
http://www.cplusplus.com/reference/algorithm/set_difference/