sen*_*iwa 6 c++ unordered-map move-semantics c++11
我已经搜索了但我只发现了有关映射值的移动构造函数的问题,但我想尝试不同的东西.
是否有可能使用std::move的键从std::unordered_map?原因很简单:我想构建一个示例,我从地图创建一个向量,尽可能少地浪费内存.我知道它会乱用地图的表示,但是,嘿,毕竟我永远不会再使用地图,所以这将是有意义的值迁出.
我的猜测是:不,我做不到.但是,我想要一些确认.
这是一个简单的代码.我希望看到移动构造函数被调用,但我有复制构造函数调用.
干杯谢谢!
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
#include <utility>
class prop
{
public:
prop(const std::string &s, int i) : s_(s), i_(i) { std::cout << "COPIED" << std::endl; };
prop(std::string &&s, int i) : s_(std::move(s)), i_(i) { std::cout << "MOVED" << std::endl; };
std::string s_;
int i_;
};
std::string gen_random(const int len) {
static const char alphanum[] =
"ABC";
std::string s;
s.resize(len);
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
return s;
}
int main()
{
const long n = 3, len = 4, max = 20;
std::unordered_map<std::string, int> map;
std::cout << ">>GENERATING" << std::endl;
for (int i = 0; i < n; i++) map[gen_random(len)]++;
if (map.size() < max)
{
std::cout << ">>MAP" << std::endl;
for (auto &p : map) std::cout << p.first << " : " << p.second << std::endl;
}
std::cout << ">>POPULATING VEC" << std::endl;
std::vector<prop> vec;
vec.reserve(map.size());
for (auto &p : map) vec.push_back(prop(p.first, p.second));
if (map.size() < max)
{
std::cout << ">>VEC" << std::endl;
for (auto &p : vec) std::cout << p.s_ << " : " << p.i_ << std::endl;
std::cout << ">>MAP" << std::endl;
for (auto &p : map) std::cout << p.first << " : " << p.second << std::endl;
}
std::cout << ">>POPULATING MOV" << std::endl;
std::vector<prop> mov;
mov.reserve(map.size());
for (auto &p : map) mov.push_back(prop(std::move(p.first), p.second));
if (map.size() < max)
{
std::cout << ">>MOV" << std::endl;
for (auto &p : mov) std::cout << p.s_ << " : " << p.i_ << std::endl;
std::cout << ">>MAP" << std::endl;
for (auto &p : map) std::cout << p.first << " : " << p.second << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量
>>GENERATING
>>MAP
CBAC : 1
BCAC : 1
BBCC : 1
>>POPULATING VEC
COPIED
COPIED
COPIED
>>VEC
CBAC : 1
BCAC : 1
BBCC : 1
>>MAP
CBAC : 1
BCAC : 1
BBCC : 1
>>POPULATING MOV
COPIED
COPIED
COPIED
>>MOV
CBAC : 1
BCAC : 1
BBCC : 1
>>MAP
CBAC : 1
BCAC : 1
BBCC : 1
Program ended with exit code: 0
Run Code Online (Sandbox Code Playgroud)
你不能移动,钥匙将被复制,因为
value_type std::pair<const Key, T>
Run Code Online (Sandbox Code Playgroud)
http://en.cppreference.com/w/cpp/container/unordered_map 所以,这里
for (auto &p : map)
Run Code Online (Sandbox Code Playgroud)
p将被推断为std::pair<const std::string, int>.
| 归档时间: |
|
| 查看次数: |
647 次 |
| 最近记录: |