g++ 4.8.2: help on vector

Nick nospam@codesniffer.com
Wed Jun 11 12:50:00 GMT 2014



On Tue, 2014-06-10 at 08:07 +0200, Francis ANDRE wrote:

> I do not understand the output of this small program usinf the <vector> 
> container.
> 
> #include <iostream>
> #include <vector>
> using namespace std;
> 
> int main() {
>      cout << "!!!Hello World!!!" << endl;
>      int i = 1;
>      int j = 2;
>      int k = 3;
>      vector<int*>    v(5);
>      v.push_back(&i);
>      v.push_back(&j);
>      v.push_back(&k);
> 
>      for( auto &n : v) {
>          cout << "int* =" << n;
>          if (n != 0)
>              cout << ", int=" << *n;
>          cout << endl;
>      }
>      return 0;
> }
> 
> !!!Hello World!!!
> int* =0
> int* =0
> int* =0
> int* =0
> int* =0
> int* =0x22aa60, int=1
> int* =0x22aa5c, int=2
> int* =0x22aa58, int=3
> 
> 
> Is this could be a bug?

The output looks right to me.  You've initialized the vector with 5
elements which will use the default initializer for the value (0 in this
case).  And then you've pushed (appended) 3 more values to the vector.
So before the loop, the vector has 8 elements:  5 zeros, and then the
addresses for the variables i, j, and k respectively.

Best regards,
Nick




More information about the Gcc-help mailing list