【发布时间】:2020-06-05 16:30:36
【问题描述】:
在下面的代码中,它仅在第一次调用appendMyList() 时附加myList,并且大小保持为1,所以有人可以在这里解释什么问题:
struct MyKey {
int accValue;
std::string name;
};
inline bool operator<(MyKey a, MyKey b){
return a.accValue < b.accValue && a.name < b.name;
}
inline bool operator==(MyKey a, MyKey b){
return a.accValue == b.accValue && a.name == b.name;
}
typedef std::map<MyKey, std::vector<int>> MyList;
class MyClass {
public:
void appendMyList(int accVal, std::string name, int element) {
myList[MyKey{accVal, name}].push_back(element);
cout<<endl<<"Size after"<< myList.size()<<endl;
}
MyList myList;
};
我看到了类似的帖子here,但我的运营商没有发现任何问题,所以我猜是别的什么?
这就是我调用函数的方式:
int main()
{
MyClass imHere;
int a = 1;
std::string yaya = "name";
for (int i = 0; i<10; i++) {
imHere.appendMyList((++a), yaya, i);
}
return 0;
};
【问题讨论】:
-
return (a.accValue < b.accValue) || (a.accValue == b.accValue && a.name < b.name); -
@cigien 我编辑了 PiotrSkotnicki 嗯,不知道你想说什么?
-
这就是你的
operator<的样子。或者,return std::tie(a.accValue, a.name) < std::tie(b.accValue, b.name); -
当
names 相同时,即使accValues 不同,您的operator<也会返回false。所以你的地图永远不会插入任何其他东西。 -
感谢帮助,== 运算符可以保持不变吗?
标签: c++ vector key stdmap multikey