C++ 将参数传递给比较器
我想传递一个映射“m”作为用于排序函数的比较器的参数C++ 将参数传递给比较器,c++,comparator,C++,Comparator,我想传递一个映射“m”作为用于排序函数的比较器的参数 bool comparator(const myType A, const myType B, map<Mytype,int> m){ return m.find(A) < m.find(B); } bool比较器(常量myType A、常量myType B、映射m){ 返回m.find(A)
bool comparator(const myType A, const myType B, map<Mytype,int> m){
return m.find(A) < m.find(B);
}
bool比较器(常量myType A、常量myType B、映射m){
返回m.find(A)
注意,比较器的变化取决于m。现在,我如何将这种比较器与排序函数一起使用呢?当我尝试下面的代码时,编译器会抱怨comparator函数中的参数数量
void SortingVector(vector<myType> V, map<myType,int> m){
sort(V.begin(),V.end(),comparator);
}
无效排序向量(向量V,映射m){
排序(V.begin()、V.end()、比较器);
}
那么,使用STD机器定义这样一个参数化比较器,最简单的方法是什么呢 使用lambda闭包:
void SortingVector(vector<myType>& V, const map<myType,int>& m){
sort(V.begin(),V.end(), [&m](const myType& A, const myType& B) {
return m.find(A) < m.find(B);
});
}
void排序向量(向量&V、常量映射&m){
排序(V.begin(),V.end(),[&m](常量myType&A,常量myType&B){
返回m.find(A)
作为旁注:为了有效性和正确性,我添加了各种引用,否则您的排序函数只会对复制的向量进行排序,并在其超出范围后将其丢弃。使用lambda闭包:
void SortingVector(vector<myType>& V, const map<myType,int>& m){
sort(V.begin(),V.end(), [&m](const myType& A, const myType& B) {
return m.find(A) < m.find(B);
});
}
void排序向量(向量&V、常量映射&m){
排序(V.begin(),V.end(),[&m](常量myType&A,常量myType&B){
返回m.find(A)
作为旁注:为了有效性和正确性,我添加了各种引用,否则您的排序函数只会对复制的向量进行排序,并在其超出范围后将其丢弃