0

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.

  • 2
    When you do `index = i ? (test[i] < test[index]) : index`, you are assigning the value of the expression `test[i] < test[index]` for all indices greater than 0, which can only be a value of `0` or `1`. Rather than the ternary, it may be better to use a simple `if` statement and assign the `index`. – Rogue Jun 21 '22 at 17:38
  • I suspect that you meant `index = (test[i] < test[index]) ? i : index;` – Drew Dormann Jun 21 '22 at 17:39
  • 1
    Related, `std::min_element` seems a decent candidate to make this entire task considerably easier. – WhozCraig Jun 21 '22 at 17:41
  • Jesus the first time I actually decided this time stackoverflow is the only help and of course it is a super embarrassing mistake :D – Sebastian Schubert Jun 21 '22 at 17:43
  • same goes for @DrewDormann – Sebastian Schubert Jun 21 '22 at 17:46
  • 2
    Side note: Get rid of all those `6`s in favour of `test.size()`. It will save you from wasting time when you change the number of items in `test`. Either you'll have to changing all of those `6`s to a different number or debug because you didn't change one or more of the `6`s to the new number. In general [avoid magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad). – user4581301 Jun 21 '22 at 17:53
  • And once you've done that, look into using iterators and range-based for loops instead. – user4581301 Jun 21 '22 at 17:54

1 Answers1

0

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;
Cride
  • 1
  • 1