Array of structures with min_element function

I’m using an array of structures like this:
struct car_data {
string Brand;
string Model;
double Price;
string Plate;
};

and in the main function I wrote:
struct car_data car_D[n];

but I get an error when I try to use the ‘min_element’ function of ‘algorithm’:
double min = *min_element(car_D.Price.begin(), car_D.Price.end());

ERROR: request for member ‘Price’ in ‘car_D’, which is of non-class type ‘car_data[n]’
NOTE: I use C++ 14 on Windows 10.

car_D is an array of car_data. So car_D.Price does not exists.

You can use a lambda with min_element to achieve what you want:

double min = *min_element(car_D.begin(), car_D.end(), [] (const car_data& a, const car_data& b) {
    return a.Price < b.Price;
});
1 Like

I tried what you suggested me but actually doesn’t work. I have now another error: request for member ‘begin’ in ‘car_D’, which is of non-class type ‘car_data [n]’
However thank you for have tried to answer my question

Firstly, use std::array<car_data, n> car_D.
Secondly, you are attempting to assign the array element obtained from the dereferenced iterator to a double, when it is actually of type car_data.

Please see https://en.cppreference.com/w/cpp/algorithm/min_element

1 Like

Thank you a lot, I understand the problem.

1 Like

No problem. Oh, please - in future, please post your question in one place and wait for a response, it’s a bit impolite to post the same question in the forum, chat and discord at the same time! :+1:

1 Like

Of course, I realize I was annoying

1 Like