2017-03-27 12 views
1

move要素を別のコンテナに簡単に入れ替えることはできますか?
私は、次の操作を実行する(<algorithm>を使用して)任意の簡単な方法を見つけることができませんでした:C++ 11リスト間の要素の移動(または他のコンテナ)

非コピー可能クラス

class NonCopyable { 
public: 
    NonCopyable() {}; 
    ~NonCopyable() {}; 
    NonCopyable(const NonCopyable&) = delete; 
    NonCopyable& operator=(const NonCopyable&) = delete; 
    NonCopyable(NonCopyable&& that) {} 
}; 

移動操作:

std::list<NonCopyable> eList; 
std::map<int, NonCopyable> eMap; 

eList.push_back(NonCopyable()); 

// Move from list to map 
{ 
    auto e = std::move(eList.back()); 
    eList.pop_back(); 
    eMap.insert(std::make_pair(1, std::move(e))); 
} 

// Move from map to list 
{ 
    auto it = eMap.find(1); 
    if (it != eMap.end()) { 
     eList.push_back(std::move(it->second)); 
     auto e = eMap.erase(it); 
    } 
} 

// Move all 
// Iterate over map?... 

私はstd::list::spliceを見て、それてきました私がlistmapを持っていて、2つではありませんので、ここで私を助けませんlist ...

ありがとう

答えて

1

std::move_iterator?ここにvectorから移動する例ですstd::string

#include <iostream> 
#include <algorithm> 
#include <vector> 
#include <iterator> 
#include <numeric> 
#include <string> 

int main() 
{ 
    std::vector<std::string> v{"this", "is", "an", "example"}; 

    std::cout << "Old contents of the vector: "; 
    for (auto& s : v) 
     std::cout << '"' << s << "\" "; 

    typedef std::vector<std::string>::iterator iter_t; 
    std::string concat = std::accumulate(
          std::move_iterator<iter_t>(v.begin()), 
          std::move_iterator<iter_t>(v.end()), 
          std::string()); // Can be simplified with std::make_move_iterator 

    std::cout << "\nConcatenated as string: " << concat << '\n' 
       << "New contents of the vector: "; 
    for (auto& s : v) 
     std::cout << '"' << s << "\" "; 
    std::cout << '\n'; 
} 

出力:

Old contents of the vector: "this" "is" "an" "example" 
Concatenated as string: thisisanexample 
New contents of the vector: "" "" "" "" 
+0

'std :: accumulate'は、' std :: pair 'と' NonCopyable'との間の変換を行い、その逆を行うことができますか? – hudac

+0

@hudac変換を実行するには、ラムダ関数を使用する必要があります。この例では、弦を結合するために累積が使用されています。あなたはおそらくそれを必要としません。 –

0

さて、あなただけ...サイクルで別のコンテナから要素を移動することができます

std::list<NonCopyable> lst; 
// ... 
std::map<std::size_t, NonCopyable> map; 
for (auto& nc: lst) { 
    map.emplace(map.size(), std::move(nc)); 
} 
// use lst.clear() here, if you so inclined 
関連する問題