我正在努力实现这样一张 map 的创建。下面的代码试图做到这一点
#include <list>
#include <map>
#include <string>
class IntWithString {
private:
int a;
std::string s;
public:
IntWithString(int a, std::string s) : a(a), s(s) {}
std::string getString() { return s; }
int getInt() { return a; }
};
namespace {
std::map<std::string, std::list<IntWithString *> > m;
}
void appendMap(IntWithString *a) {
auto it = m.find(a->getString());
if (it != m.end()) {
m[a->getString()].push_back(a);
} else {
std::list<IntWithString *> l;
l.push_back(a);
m[a->getString()] = l;
}
}
int main() {
IntWithString a(10, "ten");
IntWithString b(11, "ten");
appendMap(&a);
appendMap(&b);
return 0;
}
但是,当使用调试器查看映射 m 时,我得到一个将“十”映射到大小为 0 的列表的映射。我想要的是大小为 2 的列表。
最佳答案
我不太清楚你的意思。如果我这样做:
std::cout << m.size() << ", " << m["ten"].size() << std::endl;
我得到这个输出:
1, 2
这是一个具有一个键(“十”)和该键的两个值(10 和 11)的映射,正如预期的那样。
PS:像这样在容器中存储指针在 C++ 中并不常见。如果你真的想这样做,考虑使用 Smart Pointers .
关于c++ - 在 C++ 中生成一个字符串映射到 std::list of pointers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495598/