Faisal
Faisal

Reputation: 162

Need explanation of this, what actually is going on in this line?

I am converting some C++ code into python. but I am not sure what exactly this line do.

vector<double>().swap(prev);

I compiled a simple program to see what it actually do, I found that it resizes the vector "prev" to 0.

#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> ax;
ax.reserve(10);          
for(int i=99; i<110; ++i){
    ax.push_back(i);
}
for(int i=0; i<ax.size(); ++i){
  std::cout << ax[i] << ' ';

}

vector<int>().swap(ax);
cout<<"\nAfter space \n";
cout<<"size is "<<ax.size();

for(int i=0; i<ax.size(); ++i){
  std::cout << ax[i];

}
}

Upvotes: 3

Views: 82

Answers (1)

Bathsheba
Bathsheba

Reputation: 234665

It's the result of the programmer deciding that, for some reason,

vector<int>().swap(ax);

is clearer than

ax.clear();

(The former exchanges the initially empty anonymous temporary vector<int>() with ax).


Somewhat less cyncially perhaps, the swap method might reset the capacity of the vector, whereas clear() never does. But it's still an odd choice: if you want the capacity to be reset then use

ax.clear();
ax.shrink_to_fit();

but even that is not guaranteed to reset the capacity; it's up to the implementation to decide.

Upvotes: 7

Related Questions