c++ - 在 C++ 中生成一个字符串映射到 std::list of pointers

标签 c++ stl

我正在努力实现这样一张 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)的映射,正如预期的那样。

Live demo

PS:像这样在容器中存储指针在 C++ 中并不常见。如果你真的想这样做,考虑使用 Smart Pointers .

关于c++ - 在 C++ 中生成一个字符串映射到 std::list of pointers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495598/

相关文章:

c++ - C++模板参数中的常量表达式

c++ - 由 CreateEx() 创建的子窗口被兄弟窗口重叠

c++ - 从静态函数创建类对象

c++ - 测试迭代器是否指向最后一项?

c++ - 计算 vector 中的相似整数

c++ - cocos2d-x 中的渲染循环

c++ - 我收到错误 C2440 :

c++ - 如何为以下容器赋值?

c++ - 使用 std::map 而不是 vector<pair<string, string>> 我会看到性能提升吗?

c++ - 从 std::cin 读取密码