Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty a std::vector without change its size

Tags:

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.