将 int 映射到 C++ 中的向量结构

Mapping an int to a struct of vectors in C++

我正在尝试了解 std::map 的工作原理,我遇到了以下问题:

int id; // stores some id

struct stuff {
  std::vector<int> As;
  std::vector<int> Bs;
} stuff;

std::map<int, stuff> smap;

void foo () {
  int count = 2;
  int foo_id = 43;
  for (int i = 0; i < count; count++) {
        stuff.As.push_back(count);
        stuff.Bs.push_back(count);
  }
  smap.insert(foo_id, stuff);
}

目前我得到:

error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’
  std::map<int, stuff> smap;

error: request for member ‘insert’ in ‘smap’, which is of non-class type ‘int’
   smap.insert(int, stuff);

我希望能够将 id 映射到 struct,后者由两个在 for 循环中填充的向量组成。我究竟做错了什么?或者有更好的映射方法吗?

struct stuffstuff 定义为 struct,但 } stuff; 最后将 stuff 重新定义为 stuff 类型的变量.

struct stuff { // stuff is a struct
  std::vector<int> As;
  std::vector<int> Bs;
} stuff; // stuff is now a variable of type stuff.

因此,没有名为 stuff 的类型供 std::map<int, stuff> 使用。

您可以通过重命名结构类型来解决问题:

struct stuff_t {
  std::vector<int> As;
  std::vector<int> Bs;
} stuff;

std::map<int, stuff_t> smap;