[英]Has C++11 changed requirements for elements of STL containers, and how?
[英]c++11 moving elements between list to map (or other containers)
有沒有一種簡單的方法可以在不同容器之間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
s ...
謝謝
std::move_iterator
怎么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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.