Reputation: 6770
I want to reuse a std::vector
within a for loop. However, I need the vector to be empty for each iteration step of the for loop.
Question: How can I empty a vector rapidly without changing its capacity in the most efficient way?
What I used so far is
std::vector<int> myVec;
for(int i=0; i<A_BIG_NUMBER; ++i) {
std::vector<T>().swap(myVec);
myVec.reserve(STANDARD_MAXIMUM);
/// .. doing business
}
Cheers!
Solution:
Thanks for the answers, here is how I implemented (checked) it:
#include <vector>
#include <iostream>
int main() {
int n = 10;
std::vector< int > myVec;
myVec.reserve(n);
for(int j=0; j<3; ++j) {
myVec.clear();
for(int i=0; i<n; ++i) {
myVec.push_back(i);
}
for(int i=0; i<myVec.size(); ++i) {
std::cout << i << ": " << myVec[i] << std::endl;
}
}
return 0;
}
EDIT: changed from operator[]
to push_back
.
Upvotes: 10
Views: 8258
Reputation:
To retain the current size of a vector with default values for its content, you can assign default values to the vector. In the case of a vector of ints, you can do the following:
myVec.assign( myVec.size(), 0 );
Upvotes: 3
Reputation: 14392
Answer based on OP's solution:
The normal approach for containers is to start with an empty container and fill it up as needed with an exception for std::vector where you can reserve space eventhough there are still no objects in the container.
If you want a different approach where an "empty container" would be a container of default objects that you can access like an array (only works with std::vector and std::deque), then you need to start with resize() and you can "clean up" with fill:
int n = 10;
std::vector<int> myVec;
myVec.resize(n);
myVec[4] = 5;
std::cout << myVec[4] << "\n";
std::fill(myVec.begin(), myVec.end(), int()); // ofcourse for int, you can use 0 instead of int()
std::cout << myVec[4] << "\n";
Upvotes: 0
Reputation: 2129
use clear method as below:
std::vector<int> myVec;
for(int i=0; i<A_BIG_NUMBER; ++i)
{
std::vector<T>().swap(myVec);
myVec.reserve(STANDARD_MAXIMUM);
/// .. doing business
myVec.clear();
}
Upvotes: 2
Reputation: 38825
myVec.clear();
This is equivalent to myVec.erase(myVec.begin(), myVec.end())
.
Upvotes: 5
Reputation: 11232
Use vector::clear
method. It will clear the content without reducing its capacity.
Upvotes: 13