3

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?

6
  • 8
    This is terrible, terrible code. At the very least, use unique_ptr rather than owning raw pointers. Better yet, get rid of the unnecessary news altogether. Commented Jul 31, 2015 at 10:42
  • The last time I opened book on C++ which was roughly before C++98 such code would be normal... ))) Thank you, will go through unique_ptr... Commented Jul 31, 2015 at 11:06
  • Basically it's not even about the raw pointers. It's about using new in the first place. Commented Jul 31, 2015 at 12:52
  • It was used to illustrate the problem, however what's wrong with it (in general)? Commented Jul 31, 2015 at 13:21
  • Use vector<vector<char>> outer; instead of that vector<vector<char>*> *outer = new vector<vector<char>*>(); Commented Jul 31, 2015 at 15:42

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

will it produce the copy of the original vector?
No, it won't. It will take it by reference.
@Telokis " It will take it by reference." any reference for this point?thx
3

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.

Comments

2

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.

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.