我有一个带ID的集合,例如{3,7,1,5}。表格[7]<表格1]。我这样做了:
但是......似乎operator()无法访问表,因为table [a]或table [b]会导致segfault,而table.size()总是返回0(即使表不为空当然)。
我该怎么办?
答案 0 :(得分:0)
也许这个小样本有帮助
#include <map>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
typedef int sortkey_t;
typedef std::map<int, sortkey_t> lookup_t;
struct by_sort_lookup
{
by_sort_lookup(const lookup_t& table) : _table(table) {}
bool operator()(int a, int b) const
{
lookup_t::const_iterator ai = _table.find(a);
lookup_t::const_iterator bi = _table.find(b);
if (ai==bi) return false;
if (ai==_table.end()) return false; // choose some
if (bi==_table.end()) return true; // complementary
return (ai->second) < (bi->second);
}
private:
const lookup_t& _table;
};
int main()
{
std::map<int, sortkey_t> sortkey_by_id;
sortkey_by_id[1] = 70;
sortkey_by_id[2] = 60;
sortkey_by_id[3] = 80;
//
std::vector<int> ids;
ids.push_back(1);
ids.push_back(3);
ids.push_back(2);
std::cout << "before sorting: " << std::endl;
std::copy(ids.begin(), ids.end(), std::ostream_iterator<int>(std::cout, "\r\n"));
std::sort(ids.begin(), ids.end(), by_sort_lookup(sortkey_by_id));
std::cout << "after sorting: " << std::endl;
std::copy(ids.begin(), ids.end(), std::ostream_iterator<int>(std::cout, "\r\n"));
}