如何解决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());
}
}
,
由于您没有为MyObject
,compiler 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);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。