我试过的代码,但不起作用:
class A {
public:
struct cmpr_t {
bool operator() (int k1, int k2) {
return mp[k1] < mp[k2]; // doesn't compile
}
};
map<int, int> mp; // storing key->value
set<int, cmpr_t> ss; // just keys, ordered by corresponding value in mp
};我只想要一个map和一个set,map存储数据(键,值),而set只包含键,并且需要按键的对应值排序的set。
那么如何定义集合呢?
更新
编译器错误:
In member function ‘bool SSet::cmpr_t::operator()(int, int)’:
error: invalid use of non-static data member ‘SSet::mp’
unordered_map<int, int> mp; // k -> v
^
error: from this location
return mp[l] < mp[r];
^
error: invalid use of non-static data member ‘SSet::mp’
unordered_map<int, int> mp; // k -> v
^
error: from this location
return mp[l] < mp[r];
^发布于 2014-12-14 09:45:38
class A
{
struct cmpr_t
{
A* a;
explicit cmpr_t(A* a) : a(a) {}
// ~~~^
bool operator()(int k1, int k2) const
{
return a->mp[k1] < a->mp[k2];
// ~~^ ~~^
}
};
std::map<int, int> mp;
std::set<int, cmpr_t> ss;
public:
A() : ss(cmpr_t(this)) {}
// ~~~~~~~~~~~^
}; https://stackoverflow.com/questions/27467980
复制相似问题