简体   繁体   中英

How do you initialize a vector of distinct object pointers?

I wanted to see if I could initialize a vector of objects in a single line, so I wrote the following example:

vector<Bar*> bar(5, new Bar());

bar[3]->hit++;
for (int i = 0; i < 5; i++)
    cout << bar[i]->hit << endl;

But when I run it, I get:

1
1
1
1
1

It seems to use the same new Bar() for all the pointers. Is it possible to initialize vectors of object pointers to point to different objects?

All your pointers point to the same location, so the result is expected.

vector<Bar*> bar(5, new Bar());

doesn't create a new Bar for all 5 objects, but uses the value returned by new Bar() , which is a pointer to a memory location, to generate the vector.

To get the result you expect, you can use std::generate :

Bar* newBar() { return new Bar(); }

//...

vector<Bar*> bar(5);
std::generate(bar.begin(),bar.end(),newBar);

or simply

std::generate(bar.begin(),bar.end(), []{return new Bar();});

if C++11 is an option.

The output for this would be

0
0
0
1
0

Initializing a vector with several different values requires C++11 and the support for initializer lists:

std::vector<Bar*> v { new Bar, new Bar, new Bar, new Bar };

You can probably use a library like Boost.Assign in versions before C++11.

From the spec:

Effects: Constructs a vector with n copies of value [...]

where n is the first and value the second argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM