1

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?

Roy
  • 3,027
  • 4
  • 29
  • 43
  • 3
    you could use `std::transform`, but i doubt that it will be any faster or cleaner than what you already have, though you should reserve the right amount in the vector before calling `push_back` – 463035818_is_not_an_ai Jul 28 '17 at 16:03
  • Possibly duplicate with [C++ std::transform vector of pairs->first to new vector](https://stackoverflow.com/questions/9094132/c-stdtransform-vector-of-pairs-first-to-new-vector) – duong_dajgja Jul 28 '17 at 16:17

1 Answers1

1

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

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
  • @iyop45 for this particular piece of code `std::transform` might be a good choice without loosing the readability. But in general case too many STL algorithms in a single place do no guarantee the readability at all :) – Edgar Rokjān Jul 28 '17 at 16:17