belkipAndroidness belkipAndroidness - 3 months ago 10
C++ Question

find() returns vector subscript out of range

I have a vector of floats which include the following:

48.2701
18.868
42.9535
7
39.2046
5.09902
29


I have a piece code that finds the smallest number in the vector and returns the index:

int indexofsmallest = 2;
smallest = *min_element(distances.begin(), distances.end());
int pos = find(distances.begin(), distances.end(), smallest) - distances.begin();
indexofsmallest = pos;

cout << "||" << smallest << "||" << endl;
cout << "index of smallest is:" << indexofsmallest + 1 << endl;


however when I run, it throws a vector subscript out of range breakpoint

what am I doing wrong here?

EDIT:
enter image description here

enter image description here

Answer

Why don't you simply find the index of smallest element using:

int smallestInd = min_element(distances.begin(), distances.end()) - distances.begin();

EDIT

This is the code I have in my editor

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {

    std::vector<double> distances = { 48.2701, 18.868, 42.9535, 7, 39.2046, 5.09902, 29 };
    cout << min_element(distances.begin(), distances.end()) - distances.begin() << endl;
    return 0;
}