1

I have something where firstname_list is a vector (datatype string) of pointers. So it looks like vector <string*> firstname_list;. Inside of this, addresses of strings are stored. If I try to do something like this:

cout << *(firstname_list[0]);

It would dereference the address and give me the string I need.

However, I tried to create a loop using an iterator which I read about on this website, and I tried this:

vector<string*>::iterator iter;
for (iter = firstname_list.begin(); iter != firstname_list.end(); ++iter)
    cout << *(firstname_array[iter]);

However, now it does not print and instead gives an error:

error C2679: binary '[' : no operator found which takes a right-hand operand of type 

'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<std::basic_string<cha

r,std::char_traits<char>,std::allocator<char>> *>>>' (or there is no acceptable conversion)

I've looked at other threads similar to this where people ask how to iterate through a loop but I still couldn't figure it out. Any help as to why I am getting this message is appreciated!

StacksAndParsing
  • 119
  • 1
  • 11

1 Answers1

6

Well, if you're using C++11, then you're lucky.

for (const auto& str: firstname_list)
    std::cout << *str << std::endl;

Otherwise:

vector<string*>::iterator iter;
for (iter = firstname_list.begin(); iter != firstname_list.end(); ++iter)
    std::cout << **iter;

Note: as mentioned in the comments, you have to dereference the iterator twice. If it was pointing to a char *, then a single asterisk would be fine.

ForceBru
  • 43,482
  • 10
  • 63
  • 98