简体   繁体   中英

C++, 2D std::vector, do I need to explicitly reserve and push back empty vectors?

When I make a 2D vector. std::vector<std::vector<Pokemon>> pokemons;

Can I run this straight away: Pokemon pikachu = ... pokemons[23].push_back(Pikachu);

Or do I need to: pokemons.reserve(100); for (int i =0;i<100;i++) pokemons.push_back(vector<Pokemon>()); pokemons.reserve(100); for (int i =0;i<100;i++) pokemons.push_back(vector<Pokemon>());

Thank you

You can set the initial size of the outer vector during construction

std::vector<std::vector<Pokemon>> pokemons(100);

and it will build 100 inner empty vectors.

Can I run this straight away:

 Pokemon pikachu = ... pokemons[23].push_back(Pikachu); 

Not straight away, because your pokemons array does not have any elements yet, so pokemons[23] will be an out-of-bounds error.

Otherwise, once your pokemons array is populated, then yes, you can just push_back on one of its elements.

Or do I need to:

 pokemons.reserve(100); for (int i =0;i<100;i++) pokemons.push_back(vector<Pokemon>()); 

reserve() is only to allocate (reserve) memory for your vector, if you have a good idea of how many elements you will end up having, to avoid multiple memory allocations and potential moves. You do not need to reserve() , but it is a good idea if you will need a decent amount of memory.

Are you sure the vector is the most appropriate container you are looking for? Check How can I efficiently select a Standard Library container in C++11?

If '23' is really important, then you could for example use associative container:

 typedef std::map<int, pokemon> TPokemons;
 TPokemons pokemons;
 pokemons[23] = pikachu;

Maybe the order is not important and an unordered map would be better

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