我已经搜索过了,但我只找到关于使用映射值的移动构造函数的问题,但我想尝试一些不同的东西。是否可以使用
我的猜测是:不,我不能这样做。然而,我想得到确认。
这里是一个简单的代码。我希望看到移动构造函数被调用,但我却看到了复制构造函数的调用。
谢谢!
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;
}
输出
>>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