为什么在声明std::set时需要重复排序子程序
Why do I need to repeat the sorting subroutine when declaring a std::set?
在我的C++程序中,我试图按值而不是按键对映射进行排序。
从这个问题来看,很明显,实现这一点的方法是创建一个集合,该集合的元素是成对的,并且由我自己的小于函数排序。
以下是我尝试这样做的一些示例代码:
#include <map>
#include <set>
#include <iostream>
#include <string>
using namespace std;
bool compareCounts(const pair<string, size_t> &lhs, const pair<string, size_t> &rhs);
int main (int argc, char *argv[]) {
map <string, size_t> counter = { {"A", 1}, {"B", 2}, {"C", 3} };
set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter;
for (map<string, size_t>::iterator it = counter.begin(); it != counter.end(); ++it) {
cout << "About to add: " << it->first << ":" << it->second << endl;
auto ret = sorted_counter.insert(*it);
if (! ret.second) {
cout << "ERROR adding this element!" << endl;
} else {
cout << "Element added ok" << endl;
}
cout << "Set is of size: " << sorted_counter.size() << endl;
}
return 0;
}
bool compareCounts(const pair<string, size_t> &lhs, const pair<string, size_t> &rhs) {
return lhs.second > rhs.second;
}
这是输出:
即将添加:A:1
元素添加正常
套装大小为:1
即将添加:B:2
分段故障:11
当我添加第二个元素时,我注意到事情会崩溃。我发现发生这种情况是因为现在有必要调用我的排序子程序compareCounts
。
修复方法是更改这条线:
set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter;
到此:
set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter(compareCounts);
为什么我需要指定两次排序子程序compareCounts
?编译器不是已经从我的类型定义中知道了吗?
set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter;
您从未指定set
实际应该使用什么比较器。将以上行更改为
set <pair<string, size_t>, decltype(compareCounts) *> sorted_counter(compareCounts);
在没有指定比较器的情况下,set
默认构造一个(nullptr
),当它试图使用比较器插入第二个元素时,代码会崩溃。
你应该只使用一个函子而不是一个函数指针
struct compareCounts
{
bool operator()(const pair<string, size_t> &lhs,
const pair<string, size_t> &rhs) const
{
return lhs.second > rhs.second;
}
};
set <pair<string, size_t>, compareCounts> sorted_counter;
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 为什么在声明std::set时需要重复排序子程序