我有一個簡單的資料容器(針對這個問題進行了更多簡化),我將其用作地圖中的值。
我想知道是否有某種方法可以使用底層資料型別從映射中移動構造帶有此容器的映射作為值型別。
這是這樣一個類:
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>>>'
我想指出,我想移動構造這樣一個地圖的主要原因是為了避免創建地圖鍵值的副本。在這種情況下是一個字串。
uj5u.com熱心網友回復:
可能是這樣的(需要 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()));
}
演示。我將用戶定義的類作為地圖的鍵而不是std::string,以便我可以檢測它并確認它確實被移動而不是被復制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378906.html
