Clean the vector of each iteration of the loop. What is the most efficient way of memory?

I have a question about std :: vector.

I have an algorithm with intensive memory in which I predict that predicting the size of vectors and reserving enough memory for vectors will help me in advance with decreasing memory usage.

Which of the following is better:

for ( ... ) {
  std::vector<Type> my_vector;
  my_vector.reserve(stuff_count);
  // Do stuff , and append stuff to my_vector.
}

Or that:

std::vector my_vector;
for ( ... ) {
  my_vector.clear();
  my_vector.reserve(stuff_count);
  // Do stuff , and append stuff to my_vector.
}

Please tell me which is better, or if there is an even better way to do things.

Thank you in advance!

+5
source share
9 answers

, . . , .

, . , , .

+11

, .

, . .

+6

, .

+5

, , ?

+5

, Type /, . POD, , clear(), :

std::vector<Type> my_vector(size);
for (...)
{
  int index = 0;
  // Do stuff
  my_vector[index] = some_value;
}

(: )

+1

...

err... ?! . . , , , , .

+1

, .. stuff_count. std::vector::clear() . I.e., std::vector::capacity() std::vector::clear(), .

, . , , . , :

std::vector<type>().swap(my_vector);
my_vector.reserve(stuff_count); 

, .

+1

, std:: deque std::vector push_back.

0

?

std::vector<DataType> my_vector;
my_vector.resize(sizeof(yourData));
memcpy(reinterpret_cast<char*>(&my_vector), &yourData, sizeof(yourData));
0

All Articles