0

如何将键映射到本机数据类型,如结构?

我写了这个片段,但我无法编译它。您对如何解决它有任何想法吗?

#include <map>
#include <iostream>

typedef struct _list
{
  int a,b;
}list;
map<int,list> test_map;

int main(void)
{
  cout <<"Testing"<< endl;
}
4

6 回答 6

4

map 位于 std:: 命名空间中。解决此问题的两种可能方法:

using namespace std;
// ...
map<int, list> test_map;

或者

std::map<int, list> test_map;

我更喜欢第二种方法,但这纯粹是个人选择。

在相关的说明中,除了它们必须是可复制/可分配的,并且键类型必须具有 < 运算符(或者您也可以提供比较器函子)之外,您可以在地图中放置的内容没有真正的限制)。

编辑:似乎<list>包含在某处,无论是<iostream>(不太可能)还是<map>(奇怪但并非不可能)。using namespace std 将导致 std::list 与您自己的结构冲突。解决方案:重命名您的结构,或删除 using 命名空间并将 std:: 放在需要的位置。

于 2010-09-29T20:38:31.407 回答
2

在需要的地方添加std

重命名列表以mylist避免与std::list. 避免与常用用法冲突的类型名和变量名。

现在在VS2008中编译OK了。

#include <map>
#include <iostream>

typedef struct _list
{
    int a,b;
} mylist;

std::map<int,mylist> test_map;

int main(void)
{
    std::cout <<"Testing"<< std::endl;
    return 0;
}

在 STL 容器中使用您的结构没有问题,只要它是可复制的(复制构造函数)、可分配的(实现operator=)和可比较的(实现operator<)。

于 2010-09-29T20:43:42.847 回答
1

这里有很多问题:

  • 您缺少 a using::stdor std::map,因此编译器不知道是什么map<int,list>意思。

  • 假设您有一个using namespace std声明,您的 typedeflist可能会与同名的 STL 集合发生冲突。更改名称。

  • 您的typedef struct _tag {...} tag;构造是 80 年代的古老遗留物。这不是必需的,坦率地说相当愚蠢。它什么也得不到。

这是您修复的代码:

#include <map>
#include <iostream>

struct MyList
{
  int a,b;
};

std::map<int,MyList> test_map;

int main(void)
{
  std::cout <<"Testing"<< std::endl;
  return 0;
}
于 2010-09-29T20:46:24.090 回答
0

您似乎来自 C。试试这个:

#include <map>
#include <iostream>

struct list
{
  int a,b;
};

std::map<int,list> test_map;

int main(void)
{
  std::cout <<"Testing"<< std::endl;
  return 0;
}
于 2010-09-29T20:40:18.427 回答
0

map<int, _list> test_map;或者不要使用list(更好)作为结构的名称。(你可能也有

#include <list>
...
using namespace std;

在您的代码中的某处。

于 2010-09-29T20:43:11.693 回答
0

我会尽量避免使用键盘。

我已经用你的代码做了几个测试,看起来

  • 它添加了一个隐含的(和不需要的)using namespace std——它不需要你限定map,coutendl.
  • 它(可能)包含比您想要的更多的标准标题,包括#include <list>.

这意味着当编译器查看代码时,它会看到两个list,即您的版本和std. 由于 using 指令,两者都在您创建映射的行的范围内,编译器无法确定要使用哪个。

您可以做两件简单的事情:将简单测试的类型名称更改为list(哎呀!强制您选择命名的工具!)或完全限定使用:

#include <map>
struct list {
   int a,b;
};
std::map< int, ::list > the_map;
// ...

请注意,codepad本身添加了 include 和 using 指令,因此它也会编译:

struct list {
   int a,b;
};
map<int,::list> the_map;

但是那段代码是错误的

于 2010-09-29T23:46:46.507 回答