我试图找到最小的值和它的索引在一个向量。但是我的程序似乎给出了奇怪的结果?你可以在这里查看: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";
}
输出如下(在最后)最小值指数:1">
我期望得到值0.2及其对应的索引3。
可以试试这个for loop
static float min = std::numeric_limits<float>::max();
for (float number : your_vector) {
if (number < min)
min = number;
}
std::cout << min;