Reputation: 155
I have reserved a vector with size 40 but when i am inserted it into an unordered map as a pair then vector capacity becomes 0.Why is it so?
#include<vector>
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
std::vector<int> a;
a.reserve(40);
std::cout<<a.capacity()<<std::endl;
std::unordered_map<int,vector<int>> _map;
_map.insert(std::make_pair(1,a));
std::cout<<_map[1].capacity()<<std::endl;
return 0;
}
Upvotes: 0
Views: 134
Reputation: 10756
The make_pair
will copy construct (6) a new vector, which does not retain the capacity.
You could also instead force the move constructor (7) which does retain capacity by using std::move
but that would be overly complex.
_map.insert(std::make_pair(1, std::move(a)));
Instead of reserving capacity I'd suggest you simply reserve the size at the point of constructing the vector.
std::vector<int> a(40);
Upvotes: 3
Reputation: 206747
A copy constructed std::vector
is not required to preserve the capacity of the object it is copy constructed from. It is only required to preserve the contents.
From https://en.cppreference.com/w/cpp/container/vector/vector:
Copy constructor. Constructs the container with the copy of the contents of other.
Upvotes: 1