-1

I found some c++ code that I would like to understand. In this code they use

int airplane = min_element(min_cost_airplane.begin(),
min_cost_airplane.end()) - min_cost_airplane.begin();

But I don't know what this line of code exactly accomplishes. min_cost_airplane is a vector. I understand the min_element function, but I can't wrap my head around the -vector.begin at the end. Is the structure of this line of code common used? The thing I understand is that this line of code returns an iterator to the smallest element in the vector minus an iterator to the first element of the vector. So what does the iterator point to? Can someone please help me?

Desperate
  • 11
  • 6

3 Answers3

3

The std::min_element algorithm returns an iterator. You can dereference that iterator to access the "minimum" element of the container. If, instead, you want to know the index of the element you need to compute it as the distance from the beginning of the container.

For random-access iterators you can subtract the iterators to get the offset, or index value. That's what your example does. There's also a std::distance function that computes the index but it also works for non-random access iterators. For example:

auto iter = std::min_element(min_cost_airplane.begin(), min_cost_airplane.end());
int index = std::distance(min_cost_airplane.begin(), iter);
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
3

std::min_element returns an iterator to the first instance of the minimum value in the given range.

begin returns an iterator to the first element in the container.

The std::vector iterators are special (it's a random access iterator) in that you can subtract one from another which yields the distance between them in terms of elements (it's pointer arithmetic under the hood). To be more generic and clearer, write

auto airplane = std::distance(
    min_cost_airplane.begin(),
    std::min_element(min_cost_airplane.begin(), min_cost_airplane.end())
);
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
-3

std::min_element is used to finds the smallest element in the range [first, last].

std::vector<int> v{3, 8, 4, 2, 5, 9};
 
std::vector<int>::iterator result = std::min_element(v.begin(), v.end());
 //result iterator to the minimum value in vector v.
std::cout << "min element is: " << *result;

output: min element is: 2

Note : The smallest value in vector v is 2.

Villance
  • 41
  • 1
  • 9