2011-02-01 129 views
0
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),我想獲得數組的length.how修復它? 謝謝!C++,迭代器問題

+0

你可能想要使用const size_t len = strlen(p.second);而不是 – stijn 2011-02-01 16:10:06

+4

使用`string`! – 2011-02-01 16:15:38

+1

除了避免警告,因爲stijn建議考慮使用const_iterator,前綴increment ++ p,併爲性能和樣式點在循環外部分配end()。 – AJG85 2011-02-01 16:22:53

回答

7

我猜你的意思是

strlen(p->second); 
3
strlen(p->second) 

p是一個迭代

+0

我應該說,p是一個映射迭代器,所以你必須明確指出你想要找到值爲 – 2011-02-01 16:09:33

+1

`p.second`的長度?你確定嗎? – 2011-02-01 16:09:37

4

更妙的是使用std字符串:

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; 
} 
0

p是一對迭代器鍵 - 值。你只需要價值。

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; 
}