c ++ 11在列表到地图(​​或其他容器)之间移动元素

时间:2017-03-27 12:08:54

标签: c++ c++11 stl

不同容器之间有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 ... < / p>

由于

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

public string[] OpenExcelFileLinq(string exldir, int phone)
        {
            string sheetName = "Autoline";
            var excelFile = new ExcelQueryFactory(exldir);
            var artistAlbums = from p in excelFile.Worksheet(sheetName)
                where p["Phone"] == phone.ToString()
                select p;

            foreach (var a in artistAlbums)
            {
                string cm = a[1];
                string cn = a[2];

                if (a.Any())
                {
                    string[] cust = {cm, cn};
                    return cust;
                }
            }
            string[] notvalid = {"Not Valid", "Not Valid"};
            return notvalid;