c++ - 我可以使用转换将构造(或分配) move 到不同类型值的 map 吗?

标签 c++ c++11 type-conversion move-semantics

我有一个简单的数据容器(为了这个问题的目的进一步简化),我将其用作 map 中的值。

我想知道是否有某种方法可以从使用基础数据类型的 map 中 move 构建一个以该容器作为值类型的 map 。

下面是这样一个类:

class D
{
public:
    D() :m_value(0.0){}
    D(double value) : m_value(std::move(value)) {}
    D(const D& from) : m_value(from.m_value) {}
    D(D&& from) : m_value(std::move(from.m_value)) {}
    D& operator= (const D& from) { m_value = from.m_value; return *this; }
    D& operator= (D&& from) { m_value = std::move(from.m_value); return *this; }
    ~D() = default;

    double m_value;
};

这是我想如何转换它的一个例子。

int main() {
    std::map<std::string, double> m = { { "1", 1.0 } };

    std::map<std::string, D> m_map = std::move(m);

    return 0;
}

这会产生以下错误:

error C2440: 'initializing' : cannot convert from 'std::map<std::string,double,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' to 'std::map<std::string,D,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>'

我想指出,我想 move 构建这样一个 map 的主要原因是为了避免创建 map 键值的拷贝。在本例中是一个字符串。

最佳答案

也许是这样的(需要 C++17):

std::map<Key, long> new_m;
while (!m.empty()) {
    auto node = m.extract(m.begin());
    new_m.emplace(std::move(node.key()), std::move(node.mapped()));
}

Demo .我将一个用户定义的类作为映射的键而不是 std::string,这样我就可以检测它并确认它确实被 move 了而不是被复制了。

关于c++ - 我可以使用转换将构造(或分配) move 到不同类型值的 map 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70098010/

相关文章:

c++ - 如何将 boost 库添加到 Xcode 11? C++

C++-SDL : Blitting performance issues

c++ - Visual Studio 中包含的传递库

c++ - 热衷于在专门的模板代码中初始化静态常量成员?

类中的 C++11 线程

python - 将表示列表的字符串转换为实际的列表对象

sql - 在 SQL Server 中将 varchar 转换为日期时间

c++ - 使用 STL 算法合并 2 个 vector

c++ - 将 std::tuple 转换为 std::set

xml - 在 Powershell 中将 xml 转换为 csv 文件