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

Bli*_*ard -1 c++ stdmap

我正在努力学习如何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);
}
Run Code Online (Sandbox Code Playgroud)

目前我得到:

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);
Run Code Online (Sandbox Code Playgroud)

我希望能够映射idstruct由for循环中填充的两个向量组成的.我究竟做错了什么?或者有更好的方法来映射这个吗?

use*_*301 5

struct stuff定义stuff为a 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.
Run Code Online (Sandbox Code Playgroud)

因此,没有命名stuff的类型std::map<int, stuff>可供使用.

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

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

std::map<int, stuff_t> smap;
Run Code Online (Sandbox Code Playgroud)

  • @Blizzard在这种情况下你应该发一个新问题. (2认同)