我想按出现次数对元素进行排序。
这是我想出的(mHeights是std::multiset):
namespace{
template<class U,class T>
class HistPair{
public:
HistPair(U count,T const& el):mEl(el),mNumber(count){
}
T const& getElement()const{return mEl;}
U getCount()const{return mNumber;}
private:
T mEl;
U mNumber;
};
template<class U,class T>
bool operator <(HistPair<U,T> const& left,HistPair<U,T> const& right){
return left.getCount()< right.getCount();
}
}
std::vector<HistPair<int,double> > calcFrequentHeights(){
typedef HistPair<int,double> HeightEl;
typedef std::vector<HistPair<int,double> > Histogram;
std::set<double> unique(mHeights.begin(),mHeights.end());
Histogram res;
boostForeach(double el, unique) {
res.push_back(HeightEl(el,mHeights.count(el)));
}
std::sort(res.begin(),res.end());
std::reverse(res.begin(),res.end());
return res;
}
因此,首先我从多重集中获取所有唯一元素,然后对它们进行计数并将它们排序到一个新容器中(我需要计数,因此我使用 map )。对于这样一个简单的任务,这看起来相当复杂。
除了在其他地方也使用过的HistPair之外,没有任何可以简化此任务的STL算法,例如使用equal_range或sth。一样。
编辑:我也需要发生的次数,对不起,我忘记了这一点
最佳答案
此代码段通过组合std::set
,lambda和std::multiset::count
来实现您想要的功能:
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
int main() {
std::multiset<int> st;
st.insert(12);
st.insert(12);
st.insert(12);
st.insert(145);
st.insert(145);
st.insert(1);
st.insert(2);
std::set<int> my_set(st.begin(), st.end());
std::vector<int> my_vec(my_set.begin(), my_set.end());
std::sort(my_vec.begin(), my_vec.end(),
[&](const int &i1, const int &i2) {
return st.count(i1) < st.count(i2);
}
);
for(auto i : my_vec) {
std::cout << i << " ";
}
std::cout << std::endl;
}
您可能要反转 vector 。输出:
1 2 145 12
编辑:考虑到您还需要商品计数,可以做到这一点:
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
int main() {
typedef std::vector<std::pair<int, int>> MyVector;
std::multiset<int> st;
st.insert(12);
st.insert(12);
st.insert(12);
st.insert(145);
st.insert(145);
st.insert(1);
st.insert(2);
std::set<int> my_set(st.begin(), st.end());
MyVector my_vec;
my_vec.reserve(my_set.size());
for(auto i : my_set)
my_vec.emplace_back(i, st.count(i));
std::sort(my_vec.begin(), my_vec.end(),
[&](const MyVector::value_type &i1, const MyVector::value_type &i2) {
return i1.second < i2.second;
}
);
for(const auto &i : my_vec)
std::cout << i.first << " -> " << i.second << std::endl;
}
哪个输出:
1 -> 1
2 -> 1
145 -> 2
12 -> 3
关于c++ - 如何通过元素出现的数量对容器的多重集进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11054558/