附加使用 Struct 作为"multikey"并将 std::vector 用作映射值的映射

Appending map that uses Struct as a "multikey" and std::vector as mapped value

本文关键字:映射 vector std multikey Struct 作为 并将      更新时间:2023-10-16

下面的代码中,它仅在第一次调用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;
};

我在这里看到了类似的帖子,但没有看到我的操作员有什么问题,所以我想这是别的东西?

这就是我调用函数的方式:

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;
};
std::map

不允许存储重复项。但是,它不使用operator==来检查元素的相等性。它对两者都使用operator<- 对元素进行排序以及检查等价性

也就是说,如果!(a < b) && !(b < a)那么std::map认为ab等价的,因此使用您的operator<插入的元素不超过一个,因为name在所有元素中都是相同的,因此(a < b)(b < a)都返回false

相反,您应该使用:

inline bool operator<(MyKey a, MyKey b) {
return a.accValue < b.accValue || (a.accValue == b.accValue && a.name < b.name);
}

或:

inline bool operator<(MyKey a, MyKey b) {
return std::tie(a.accValue, a.name) < std::tie(b.accValue, b.name);
}