I have a vector containing objects:
std::vector<myObjectType> myObjectVector;
myObjectType contains a double member variable called value, which I can retrieve in two ways:
myObjectType aObject;
double aObjectDouble = aObject(); // possibility 1 (overloaded operator)
double aObjectDouble = aObject.get_value(); // possibility 2
Now I can convert the std::vector<myObjectType> myObjectVector into std::vector<double> myObjectVectorDoubles, where the std::vector<double> contains the double values of each object as follows:
std::vector<double> myObjectVectorDoubles;
myObjectVectorDoubles.push_back(myObjectVector[0].get_value());
myObjectVectorDoubles.push_back(myObjectVector[1].get_value());
...
...
or simply this way
std::vector<double> myObjectVectorDoubles;
myObjectVectorDoubles.push_back(myObjectVector[0]());
myObjectVectorDoubles.push_back(myObjectVector[1]());
...
...
I can put this in a for loop, but is this the cleanest (or most efficient) solution?
You could use std::transform. For example if you have a class
class Foo {
double val;
public:
Foo() = default;
Foo(double const val_) : val(val_) {}
double getVal() const { return val; }
};
In your program do:
std::vector<Foo> v {{1.2}, {2.3}, {5.6}};
std::vector<double> dv(v.size());
std::transform(v.begin(), v.end(), dv.begin(), [](auto const &f) { return f.getVal(); });
Live Demo
If your compiler doesn't support C++14 generic lambdas change to:
std::transform(v.begin(), v.end(), dv.begin(), [](Foo const &f) { return f.getVal(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With