Empty a std :: vector without changing its size

I want to reuse std::vector

in a for loop. However, I need the vector to be empty for each iteration step of the for loop.

Question: How can I quickly free a vector without changing its capacity in the most efficient way?

What I have 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
}

      

Hooray!

Decision:

Thanks for the answers, this is how I implemented (tested) 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

.

+3


source to share


5 answers


Use the method vector::clear

. It will clean up the content without decreasing its capacity.



+9


source


myVec.clear();

      



This is equivalent myVec.erase(myVec.begin(), myVec.end())

.

+4


source


use the cleaning 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();
    }

      

+2


source


Answer based on OP's solution: The
usual approach for containers is to start with an empty container and fill it as needed, with an exception for std :: vector where you can reserve space even though there are no objects in the container yet.
If you want a different approach where the "empty container" is the default container of objects that you can access like an array (only works with std :: vector and std :: deque), you need to start by resizing () and you can "clear" 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";

      

0


source


To keep the current size of the vector with default values ​​for its content, you can assign default values ​​to the vector. In the case of vector ints, you can do the following:

myVec.assign( myVec.size(), 0 );

      

0


source







All Articles