Reputation: 105
I have a pretty trivial question but I can't find anything on the internet covering it. I need to find the index in a 1D array where the minimum value is stored. Everything I found so far only tells you the value of the minimum value. Code I made an attempt with is:
int min_element_loc (double a[]){
double first, last;
first = a[0];
last = a[255];
for(int i = 0;i<256;i++)
{
if (first==last) return i;
double smallest = first;
while (++first!=last)
smallest=first;
return i;
}
return 0;
}
(The array has 256 elements in it : I know its messy but it will never change, and the program is not in final version)
Thanks
Upvotes: 0
Views: 98
Reputation: 934
Use std::min_element found in the algorithm header.
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<double> vals = { 1.0, 2.0, 0.5, 4.2 };
auto iter = std::min_element(vals.begin(), vals.end());
auto idx = iter - vals.begin();
std::cout << idx << "\n";
return 0;
}
Upvotes: 3