0

I keep getting an error while running this code. I've searched for a solution for similar errors, but as a junior programmer, I can't understand solutions meant to be for different codes. Here is my code. Please give me a solution with demonstration.

#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;

int main() {
        vector <int> listed_elements {10,6,11};
        auto min_value = min_element(listed_elements.begin(), listed_elements.end()); 
        cout << "The smallest element on the list is: ";
        cout << min_value << endl;

        return 0;
        }
Mightnare
  • 5
  • 3
  • I suspect that the problem is that you've literally been searching for *converting*, and that's not what you want to do. Check out the [book list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Oct 07 '20 at 12:30
  • If you want the value referenced by the iterator, use `*min_value` (after checking that `min_value != listed_elements.end()`, to avoid undefined behaviour) If you want to convert into an index (where `0` corresponds to the first element) do `std::distance(listed_elements.begin(), min_value)`. – Peter Oct 07 '20 at 12:30
  • @Peter `std::min_element` never returns `end` does it? Anyhow I will add a note to the answer... – 463035818_is_not_an_ai Oct 07 '20 at 12:53
  • @Peter it does in case the range is empty – 463035818_is_not_an_ai Oct 07 '20 at 12:56
  • @idclev463035818 - Indeed. An alternative test in that case is that the vector is not empty. – Peter Oct 08 '20 at 08:49

1 Answers1

0

Iterators mimick pointers. You can dereference the iterator to get the element:

cout << *min_value << endl;

Note that in general algorithms often return end (the iterator you passed as second parameter) to signal that no element was found and then you need to check that you have a valid iterator before dereferencing it:

if (min_value != listed_elements.end()) {
    std::cout << *min_value << std::endl;
}

However, the only case where std::min_element returns the end iterator is when the range is empty, so in case you are absolutely certain that this isn't the case you can drop that check (but only then!).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185