What is really empty std :: vector in C ++?

I have two vectors in class A that contain other objects of class B and C. I know for sure how many elements these vectors must hold maximum. In the class A constructor initializer list, I initialize these vectors to their maximum sizes (constants).

If I understand this correctly, now I have a vector of class B objects that have been initialized using their default constructor. Correctly? When I wrote this code, I thought this was the only way to handle things. However, since then I have learned about std::vector.reserve(), and I would like to achieve something else.

I would like to allocate memory so that these vectors become as large as possible, because adding to them is controlled by user input, so I do not want frequent changes. However, I repeat this vector many, many times per second, and I am only now working on objects marked as “active”. In order to check the B / C class logic element at each iteration, this is stupid. I do not want these objects to even be where my iterators could see when I look at this list.

Is reserving maximum space ahead of time and using push_backto add a new vector to a vector - is this a solution?

+3
source share
3 answers

A vector . - , . - , . A vector , 0. , size() 0 empty() true. vector ( , , vector ). capacity() - , vector, , .

, vector, . vector . vector, , vector - max_size() - max_size(), /, vector ( , ). , vector, , vector. , vector, vector , , , ( vector, , ), . vector. , , .

, vector , , , reserve(), . , , , vector. , , , , , . . , .

vector , , , . vector , (, ) , , . , reserve(). , reserve(), , . , vector , , - vector , .

, :

capacity()  // Returns the number of elements that the vector can hold
reserve()   // Sets the minimum capacity of the vector.

, :

clear()  // Removes all elements from the vector.
empty()  // Returns true if the vector has no elements.
resize() // Changes the size of the vector.
size()  // Returns the number of items in the vector.
+12

, reserve(n) - capacity() size().

BTW, " " , "insert X", X , . , , .

+4

, , , , .

, vector<B>, . vec.reserve(100). vec 0 . . vec.empty() true vec.size() 0. , push_back, , vec 100 , .

+1

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


All Articles