C++11 在列表到映射(或其他容器)之间移动元素
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
......
谢谢
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
相关文章:
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 比较它们之间的元素并获取公共值的键
- 查找多个向量之间的公共元素(无整数元素)
- 常量映射和常量元素映射之间的区别
- r-在Rcpp和C++之间转换矢量(使用Rcpp::as或Rcpp:::wrap)是否会创建一个新的矢量并复制元素
- 使用折叠表达式打印每个元素之间的空格
- 如何计算大小为 1000 x 1000 的 2D 数组中 2 个元素之间的步幅?C++
- OpenCV 文件存储 - 错误:元素之间的解析错误 (icvYMLParseValue) 缺失
- 在查找子集中元素和元素数量之间的二进制比较背后的逻辑是什么?
- 使用动态创建的选项卡元素在C 和QML之间绑定
- C++11 在列表到映射(或其他容器)之间移动元素
- 从 1 中创建新的字符 * 作为参数,元素位于 2 个索引之间
- 如何在对一组中的一对之间找到一个元素
- C++ - 前两个元素之间的差异
- 字符串和向量<string>元素之间的区别
- 在两个std::向量之间匹配元素
- 如何删除给定索引之间的所有元素
- 当我删除数组时,指针在哪里?指向数组的指针与数组中的元素之间的区别
- 为什么指针减法会导致介于两者之间的元素数量
- 在给定某些约束的情况下,求出元素之间的最大距离