gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:33:20 26 4
gpt4 key购买 nike

有没有简单的方法来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: "" "" "" ""

关于c++11 在列表之间移动元素以映射(或其他容器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43046032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com