为什么这个代码有问题(在visual studio 2010中)?
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
int main() {
map<string,int> map;
map<string,int>::iterator iter = map.begin();
}
Run Code Online (Sandbox Code Playgroud)
它只是告诉我迭代器定义中存在一个问题(类模板"std :: iterator"的参数列表缺失),但是我看到了这样写的样本.
wkl*_*wkl 11
您调用了您的变量,map并且您使用了using namespace std;这将导致名称查找问题,因为您正在使用变量和名为同一事物的库容器.大卫在评论和下面解释了这一部分.
你可以做几件事(除了这些之外你还可以做更多):
使用符合条件限定变量声明 std::
std::map<string, int> map;
std::map<string, int>::iterator iter = map.begin();
放下using namespace std;并限定所有内容std::
map变量.实际上,您应该避免使用库定义的名称作为变量名.编辑:马克的答案也适合你.
嗯,我想知道编译器是否满意:
typedef map<string,int> MapType;
MapType myMap;
MapType::iterator iter = myMap.begin();
Run Code Online (Sandbox Code Playgroud)
无论如何,我会倾向于这一点,因为它减少了干燥,对我来说看起来更干净.
此外,变量名称map可能会使编译器感到困惑,并且至少可能会混淆人类阅读代码,因此我会改变它.