vector <map <string,MyObject>列表在C ++中插入数据

问题描述

我有两个vector<map<string,MyObject>>类型的数据,我想移动或复制一些MyObject数据以在C ++中复制另一个相同类型的数据,如下所示:

using namespace std;

struct MyObject{
  string id;
  string name;
  string phone;
  string salary;
};

//Somewhere else have below type.
vector<map<string,MyObject>> v1;
vector<map<string,MyObject>> v2;

如何执行上述操作?

解决方法

一个简单的例子,我将类型更改为std::vector<Myobject>,而不是您的map的复杂向量。

#include <iostream>
#include <string>
#include <vector>

int main()
{
    using std::string;
    using std::vector;

    struct MyObject {
        string id;
        string name;
        string phone;
        string salary;

        MyObject copyidname() {
            MyObject obj{ id,name,"","" };
            return obj;
        }
    };
    // Simplifiled type to demonstrate copy
    vector<MyObject> v1;
    v1.push_back( MyObject{ "1","1","1" });
    vector<MyObject> v2;

    // Set capacity to prevent reallocation.
    v2.reserve(v1.size());
    for (auto it = v1.begin(); it != v1.end(); ++it) {
        v2.push_back(it->copyidname());
    }
}
,

由于您没有为MyObjectcompiler will generate necessary move-copy constructors for you提供任何构造函数。

所以不用担心,只要做

v2 = v1;

要复制

v2 = std::move(v1);

移动


对于条件副本,您可以使用<algorithm>标头中的std::copy_if算法。

对于条件移动(move_if),您可以修改以上算法,如this post所示:

template <class InputIt,class OutputIt,class UnaryPredicate>
OutputIt move_if(InputIt first,InputIt last,OutputIt d_first,UnaryPredicate pred)
{
    return std::copy_if(std::make_move_iterator(first),std::make_move_iterator(last),d_first,pred);
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...