动漫网站设计模板,电商网站制作教程,企业网站怎样做可以搜索到,怎么让网站页面自适应文章目录 使用sort对容器内元素进行排序在类中如何调用自定义的成员函数进行排序错误原因#xff1a;解决办法#xff1a;使用Lambda表达式#xff1a; 使用sort对容器内元素进行排序
std::sort()函数专门用来对容器或普通数组中指定范围内的元素进行排序#xff0c;排序规… 文章目录 使用sort对容器内元素进行排序在类中如何调用自定义的成员函数进行排序错误原因解决办法使用Lambda表达式 使用sort对容器内元素进行排序
std::sort()函数专门用来对容器或普通数组中指定范围内的元素进行排序排序规则默认以元素值的大小做升序排序。sort() 只对 array、vector、deque 这 3 个容器提供支持可以自定义排序函数
#include iostream
#include vector
#include algorithm// Define the pair type
typedef std::pairuint32_t, uint64_t PairType;// Comparator function to compare pairs based on the second element (value)
bool comparePairs(const PairType p1, const PairType p2) {return p1.second p2.second;
}int main() {// Create the vector of pairsstd::vectorPairType vec {{1, 100}, // idx1, value100{2, 50}, // idx2, value50{3, 200}, // idx3, value200// Add more pairs here if needed};// Sort the vector using the comparator functionstd::sort(vec.begin(), vec.end(), comparePairs);// Output the sorted vectorfor (const auto pair : vec) {std::cout idx: pair.first , value: pair.second std::endl;}return 0;
}comparePairs是我们自定义的函数sort 第三个三处 std::sort(vec.begin(), vec.end(), comparePairs);在类中如何调用自定义的成员函数进行排序
typedef std::pairuint32_t, uint64_t PairType;bool MySort::comparePairs(const PairType p1, const PairType p2) {return p1.second p2.second;
}bool MySort::sort_fun(vectorPairType vec)
{std::sort(vec.begin(), vec.end(), comparePairs); //报错
}Visual Studio 报错
C3867 “MySort::compareParis”: 非标准语法请使用 来创建指向成员的指针
C2672 “std::sort”: 未找到匹配的重载函数
C2780 “void std::sort(const _RanIt,const _RanIt)”: 应输入 2 个参数却提供了 3 个错误原因
这个错误是因为在使用std::sort()时传递了一个成员函数指针而非普通函数指针
解决办法使用Lambda表达式
修改后的代码
typedef std::pairuint32_t, uint64_t PairType;bool MySort::comparePairs(const PairType p1, const PairType p2) {return p1.second p2.second;
}bool MySort::sort_fun(vectorPairType vec)
{// 定义Lambda表达式auto sortLambda [this](const PairType p1, const PairType p2) {return this-comparePairs(a, b);};std::sort(vec.begin(), vec.end(), sortLambda);
}