C ++ 11 based on pointer vector

I just compiled GCC 4.6.0, and I wanted to try new features, starting with a range-based loop.
The first loop I wanted to change was to repeat the std :: vector pointers. I changed the code to use the new syntax, but it did not compile.

I tried replacing another for loop that was on std :: vector structures, and it compiled and works fine.

Here is a short test code to show you my problem:

#include <vector> #include <iostream> int main() { std::vector< int > values; values.push_back(2); values.push_back(5); values.push_back(8); values.push_back(13); values.push_back(17); for (int &n : values) { std::cout << n << "\n"; } std::vector< int* > pointers; pointers.push_back(new int(2)); pointers.push_back(new int(5)); pointers.push_back(new int(8)); pointers.push_back(new int(13)); pointers.push_back(new int(17)); for ((int*) &p : values) { std::cout << (*p) << "\n"; } for( unsigned int i = 0; i < pointers.size(); ++i) { delete pointers[i]; } return 0; } 

When I try to compile it (yes, I give -std = C ++ 0x as a parameter for g ++), it dies with this error:
main.cpp|27|error: found ':' in nested-name-specifier, expected '::'
If I comment on lines 27-30, that's OK.

What am I doing wrong? Isn't the pointer reference right? Or is there a restriction on the contained types in which ranges can be used for loops?

Thanks for any help!

+6
source share
2 answers
 for ((int*) &p : values) 

It is not right. (int*) is an expression alone, so you need to do int*& (without parentheses, which makes the expression - otherwise called not a type name), at least to make it correct. I prefer to use auto or auto &, personally.

You can do:

 for (auto p : values) // here p is a pointer, a copy of each pointer 

or

 for (auto& p : values ) // here p is a non-const reference to a pointer 

or

 for ( int* p : values ) // here p is a copy of each pointer 

or in the general code:

 for ( auto&& p: values ) // p is either a const reference to what is in values, or a non-const reference, depends on the context 
+13
source

I think you wanted to iterate over "pointers" instead of "values" ...

0
source

Source: https://habr.com/ru/post/886173/


All Articles