Roy
Roy

Reputation: 3267

Get vector of a specific member from a vector of structs

I have a vector of structs as follows. The struct holds the relevant data for a plot.

struct DATA_T
{
    double x;
    double y;
    double z;
}

std::vector<DATA_T> results;

I need to be able to retrieve all the x values within results vector and store them as a vector of doubles

I know that I could create these vector programmatically.

std::vector<double> x_values;
x_values.reserve(results.size());
for(auto const &data : results)
{
    x_values.push_back(data.x);
}

However, I was wondering if there is a more concise solution. Perhaps using a similar approach to how I can search for specific data points using find_if?

Upvotes: 1

Views: 1091

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

You could use std::transform for that providing it with appropriate lambda to retrieve x:

std::vector<double> x_values;
x_values.reserve(results.size());

std::transform(std::cbegin(results), std::cend(results),
    std::back_inserter(x_values),
    [](const auto& data) {
        return data.x;
    }
);

DEMO

Upvotes: 1

Related Questions