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

10,788

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
10,788
Lu4
Author by

Lu4

Updated on June 26, 2022

Comments

  • Lu4
    Lu4 almost 2 years

    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?