I am trying to find the smallest value and its index in a vector. But my programm seem to give weird results? You can check it out here: http://cpp.sh/5qj7r
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main()
{
std::vector<float> const test{5.5,4.,3.,0.2,7.,5.};
for (int i=0;i<6;++i)
{
std::cout << "test[i="<< i <<"]: " << test[i] << "\n";
}
size_t index{0};
for (size_t i{0}; i < 6U; ++i)
{
std::cout << "test[i="<<i<<"]: " << test[i]<<"\n";
std::cout << "old min: "<< test[index] <<"\n";
std::cout << "old index: "<< index <<"\n";
std::cout << "test[i] is smaller old min: ";
std::cout << std::boolalpha;
std::cout << (test[i] < test[index]) << "\n";
index = i ? (test[i] < test[index]) : index;
std::cout << "new min: "<< test[index] <<"\n";
std::cout << "new index: "<< index <<"\n";
}
std::cout << "Index of Smallest Value: " << index<<"\n";
}
The output is the following (at the very end) "Index of Smallest Value: 1"
I expect to get the value 0.2 and its corresponding index 3.
maybe try it with this for loop
static float min = std::numeric_limits<float>::max();
for (float number : your_vector) {
if (number < min)
min = number;
}
std::cout << min;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.