Josh Morrison
Josh Morrison

Reputation: 7636

C++, iterator question

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!

Upvotes: 0

Views: 240

Answers (5)

jay bhaskar
jay bhaskar

Reputation: 11

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

Upvotes: 1

Kos
Kos

Reputation: 364

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

Upvotes: 0

programmersbook
programmersbook

Reputation: 4094

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

Upvotes: 4

Foo Bah
Foo Bah

Reputation: 26251

strlen(p->second)

p is an iterator

Upvotes: 3

eddyxu
eddyxu

Reputation: 658

I guess what you mean is

strlen(p->second);

Upvotes: 7

Related Questions