2013-11-21 27 views
5

我已經搜查,但我只發現了大約與映射值移動構造函數的問題,但我想嘗試不同的東西。移動鍵unordered_map

是否有可能使用std::movestd::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 
+0

只是*鍵*,而不是該密鑰的數據? –

+0

是的,只是關鍵。不過,我也可以解決這個問題。 – senseiwa

回答

5

不能移動,鑰匙將被複制,因爲

value_type std::pair<const Key, T> 

http://en.cppreference.com/w/cpp/container/unordered_map 所以,這裏

for (auto &p : map) 

p將推導爲std::pair<const std::string, int>

+4

但我們試圖讓它:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3586.pdf –