我正在尝试将键和值数据添加到我的类映射成员变量中 - 但它不会添加相同的 - 我尝试了映射 - 插入、[] 和 emplace 方法,但它们没有将数据添加到我的循环代码中的映射- 只有我在类构造期间插入的值可用 - 我需要做些什么来解决这个问题 - 我期望 show 方法也会打印 7, 8,9, 9 -
#include <iostream>
#include <map>
#include <vector>
class A {
public:
A(std::initializer_list <uint32_t> d): data(d) {}
std::vector <uint32_t> data;
bool operator < (const A & rhs) const {
size_t rhsSize = rhs.data.size();
for (size_t i = 0; i < data.size(); i++) {
if (i < rhsSize)
return false;
return true;
}
}
};
class B {
public:
B(const std::map <A, uint32_t> & t): table(t) {}
void Show() {
for (std::map <A, uint32_t> ::iterator it = table.begin(); it != table.end(); ++it) {
for (const auto & i: it->first.data)
std::cout << i << "\n";
std::cout << it->second << "\n";
}
}
std::map <A, uint32_t> table;
};
int main() {
std::map <A, uint32_t> tb = {
{
A {70, 8, 9,10}, 1234}
};
B b(tb);
for (int i = 0; i < 2; i++) {
b.Show();
b.table.emplace(A {7, 8,9, 9}, 1234);
}
return 0;
}
编译并运行代码:
$ c++ -std=c++11 try78.cpp
$ ./a.exe
70
8
9
10
1234
70
8
9
10
1234
最佳答案
你的 operator <
违反了 std::map
的严格弱排序要求需要 key 。这需要如果 comp(a,b)
那么comp(b,a)
为真是假的。你用
bool operator < (const A & rhs) const {
size_t rhsSize = rhs.data.size();
for (size_t i = 0; i < data.size(); i++) {
if (i < rhsSize)
return false;
return true;
}
}
比较元素,如果我们比较{70, 8, 9,10}
反对{7, 8,9, 9}
然后返回 true
如果我们翻转它,它也会返回 true
.这使得 map 认为元素是相等的,它不会添加第二个项目。
如果您只是为了确保唯一 vector 存储在 map 中,那么您可以使用 std::vector
的 operator <
在 A
的 operator <
喜欢
bool operator < (const A & rhs) const {
return data < rhs.data;
}
代码将正常运行。
关于c++ - std::map 为什么不在我的代码中添加键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54656388/