Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ convert vector containing objects to vector containing doubles

Tags:

c++

vector

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?

like image 568
Pietair Avatar asked Nov 22 '25 08:11

Pietair


1 Answers

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(); });
like image 171
101010 Avatar answered Nov 23 '25 22:11

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!