当我将它插入到无序映射中时,向量的容量为 0
capacity of vector is 0 when i am inserting it into an un-ordered map
我保留了一个大小为 40 的向量,但是当我将它作为一对插入到无序映射中时,向量容量变为 0.Why 是这样吗?
#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;
}
make_pair
将复制构造 (6) a new vector, which does not retain the capacity。
您也可以使用 std::move
强制移动构造函数 (7) which does retain capacity,但这会过于复杂。
_map.insert(std::make_pair(1, std::move(a)));
我建议您不要保留容量,而只是在构建向量时保留大小。
std::vector<int> a(40);
构造的副本 std::vector
不需要保留从其构造副本的对象的容量。只要求保留内容。
来自https://en.cppreference.com/w/cpp/container/vector/vector:
Copy constructor. Constructs the container with the copy of the contents of other.
我保留了一个大小为 40 的向量,但是当我将它作为一对插入到无序映射中时,向量容量变为 0.Why 是这样吗?
#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;
}
make_pair
将复制构造 (6) a new vector, which does not retain the capacity。
您也可以使用 std::move
强制移动构造函数 (7) which does retain capacity,但这会过于复杂。
_map.insert(std::make_pair(1, std::move(a)));
我建议您不要保留容量,而只是在构建向量时保留大小。
std::vector<int> a(40);
构造的副本 std::vector
不需要保留从其构造副本的对象的容量。只要求保留内容。
来自https://en.cppreference.com/w/cpp/container/vector/vector:
Copy constructor. Constructs the container with the copy of the contents of other.