Lu4
Lu4

Reputation: 15032

Range based for loop with pointer to vector in C++11

Consider the following example:

vector<vector<char>*> *outer = new vector<vector<char>*>();
{
    vector<char> *inner = new vector<char>();

    inner->push_back(0);
    inner->push_back(1);
    inner->push_back(2);

    outer->push_back(inner);

    inner->push_back(3);
}

auto x = outer->at(0);

for (auto c : x) {
    cout << c << ",";
}

I would like to iterate through the values of the vector<char>*; how can I accomplish that?

Upvotes: 3

Views: 15582

Answers (3)

Niall
Niall

Reputation: 30605

The type of x is vector<char>* so you need to iterate over what is pointed to by x; you need to dereference x.

for (auto&& c : *x) {
//              ^ dereference the container for a range
//       ^ note the use of &&

As a side note;

  • the characters for the integer values 0, 1 etc. are not printable, I'd test with 0x31 etc or just push back characters '0', '1' etc.
  • it is generally preferable to use auto&& in the range based for loops to avoid copies or subtle bugs when the container returns proxy object.

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

Here is a demonstrative program

#include <iostream>
#include <vector>
#include <cstring>

int main()
{
    const char *s = "Hello Lu4";
    std::vector<std::vector<char> *> *v = 
        new std::vector<std::vector<char> *>( 1, new std::vector<char>( s, s + std::strlen( s ) ) );

    for ( char c : *( *v )[0] ) std::cout << c;
    std::cout << std::endl;

    for ( auto p : *v ) delete p;
    delete v;
}    

The program output is

Hello Lu4

Also you could use the following loop

for ( auto inner : *v )
{
    for ( char c : *inner ) std::cout << c;
    std::cout << std::endl;
}        

If to use this loop in the demonstrative program you will get the same result as above because the "outer" vector contains only one element with index 0.

Upvotes: 2

Telokis
Telokis

Reputation: 3389

Why don't you simply dereference x?

for (auto c : *x) { // Here
    cout << c << ",";
}

It will take *xby reference and, so, won't make a copy.

Upvotes: 9

Related Questions