I have a struct MyStruct which have some elements (including int value1), and a std::vector<MyStruct>. How can I pick up all value1 from each MyStruct and have a std::vector<int> which is the vector of value1. No write will be operated on the new vector.
The following is possible but the copy is needed. Is there any solution to avoid it?
struct MyStruct{
int value1;
int value2
};
std::vector<MyStruct> myStruct = func1();
std::vector<int> ans;
for (auto i:myStruct)
{
ans.push_back(i.value1);
}
func2(ans); // In `func2` there is no write on `ans`.
CodePudding user response:
struct data attributes are public by default and you can just store the pointer to the values in a new vector. It should look something like this:
std::vector<int*> ans;
for(auto i: myStruct){
ans.push_back(&i.value1);
}
func2(ans);
Note that here you have to change func2 so that it takes as an argument a vector of integer pointers rather than a vector of integers. Then, you can access each integer using the dereference operator:
*ans[i]
I believe a more optimal solution would be to change the func2 to take in a &std::vector<MyStruct> as an argument by reference so that no copy is made. Then you can just access each element by myStruct[i].value1.
CodePudding user response:
Here you are:
auto ret = f();
std::vector<int> ans;
ans.reserve(ret.size());
for (auto const& elem : ret) {
ans.emplace_back(elem.value1);
}
emplace_back constructs the element directly from the argument elem.value1 unlike push_back which constructs it from a copy created from the same argument namely elem.value1.
CodePudding user response:
What you want is reference type and not just any type but reference of reference and that is exactly where pointers come into picture
std::vector<int*> ans;
for (int i = 0; i < myStruct.size(); i )
{
ans.push_back(&myStruct.at(i).value1);
}
try this and please let me know it should solve your issue
