C ++,迭代器问题

时间:2011-02-01 16:06:23

标签: c++ iterator

map <int, char*> testmap;
testmap[1] = "123";
testmap[2] = "007";
map<int, char*>::iterator p;

for(p = my_map.begin(); p != my_map.end(); p++) {
int len = strlen(p); // error here, why? thanks
cout << len << endl;
  cout << p->first << " : ";
  cout << p->second << endl;
}

我在这个谎言上得到错误:int len = strlen(p),我想得到数组的长度。如何修复它? 谢谢!

5 个答案:

答案 0 :(得分:7)

我猜你的意思是

strlen(p->second);

答案 1 :(得分:4)

更好用std string:

map <int, std::string> testmap;
testmap[1] = "123";
testmap[2] = "007";
map<int, std::string>::iterator p;

for(p = testmap.begin(); p != testmap.end(); p++) {
    int len = p->second.size();
    cout << len << endl;
    cout << p->first << " : ";
    cout << p->second << endl;
}

答案 2 :(得分:3)

strlen(p->second)

p是一个迭代器

答案 3 :(得分:1)

map <int, char*> testmap;
testmap[1] = "123";
testmap[2] = "007";
map<int, char*>::iterator p;

for(p = my_map.begin(); p != my_map.end(); p++) {
    int len = std::iterator_traits<p>::value_type.size();
    cout << len << endl;
    cout << p->first << " : ";
    cout << p->second << endl;
}

答案 4 :(得分:0)

p是对键值的迭代器。你只需要价值。