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

I got error on this lie: int len = strlen(p), I wang to get array's length.how to fix it? Thank you!

2
  • you might want to use const size_t len = strlen( p.second ); instead Commented Feb 1, 2011 at 16:10
  • 1
    In addition to avoiding the warning as stijn suggests consider using const_iterator, prefix increment ++p, and assigning end() outside of loop for performance and style points. Commented Feb 1, 2011 at 16:22

5 Answers 5

7

I guess what you mean is

strlen(p->second);
Sign up to request clarification or add additional context in comments.

Comments

4

Even better use 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;
}

1 Comment

+42: For crap's sake, don't use old, crusty C-style char* strings with maps. Actually, don't use them in C++ at all.
3
strlen(p->second)

p is an iterator

4 Comments

i should say, p is a map iterator, so you have to explicitly point out that you want to find the length of the value
p.second? Are you sure about that?
map iterators return an iterator of type pair<key,value>
map iterators return an address to the pair<key, value>
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;
}

1 Comment

Explanation would be helpful.
0

p is an iterator for a pair key-value. And you need only value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.