C++11 在列表到映射(或其他容器)之间移动元素

c++11 moving elements between list to map (or other containers)

本文关键字:之间 元素 移动 其他 列表 映射 C++11      更新时间:2023-10-16

有没有一种简单的方法可以在不同的容器之间move元素?
我找不到任何简单的方法(使用<algorithm>(执行以下操作:

不可复制的类

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但它在这里对我没有帮助,因为我有一个list和一个map,而不是两个list......

谢谢

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: "" "" "" ""

好吧,你可以...在一个循环中将元素从一个容器移动到另一个容器:

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