Reputation: 81
I have two vector<map<string,MyObject>>
type data and I want to move or copy some of MyObject
data to copy another in the same type in C++ like below:
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;
How can I perform the above-given operation?
Upvotes: 0
Views: 97
Reputation: 2578
A simple example, I change type to std::vector<Myobject>
instead of your complext vector of 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","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());
}
}
Upvotes: 1
Reputation: 1356
Since you have not provide any constructor to MyObject
, compiler will generate necessary move-copy constructors for you.
So no worries, just do
v2 = v1;
for copy
v2 = std::move(v1);
for move
For the conditional copy you can use std::copy_if
algorithum from <algorithm>
header.
For the conditional move (move_if) you can modify the above algorithm like shown in 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);
}
Upvotes: 0