Search code examples
c++c++11templatespointerscomparable

Comparables in vectors. My code doesn't seem to be pulling the correct values


#include <vector>
#include <string>
template <typename Comparable>
const Comparable & findKthLargest( const std::vector<Comparable> & v, const int k){

int counter;
Comparable j;
for (Comparable i : v){
    counter = 0;
    j = v[i];
    for(Comparable p : v){
        if(v[p] > j){
            counter++;
        }
    }

    if(counter == k){
        return v[i];
    }
}
return -1;
}

I am passed a vector of comparables and an integer k. I need to find the "kth" largest comparable in the array given. This code works by iterating through the vector one comparable at a time and checking how many other comparables in the vector are larger than it. (the largest element in the array would yield 0, second largest would yield 1). So for example:

I am passed the vector:

{ 5,4,7,6,3,8,4,9 }

and the tests run are:

REQUIRE( findKthLargest(kth_ints, 0) == 9);
REQUIRE( findKthLargest(kth_ints, 1) == 8);
REQUIRE( findKthLargest(kth_ints, 3) == 6);

I am passing the first two, and not the third one(I think I'm getting 4 instead of 6). I think I should be using pointers here to pull the actual value from the vector rather than the address, but I'm unfamiliar with the syntax for doing so, or where exactly I would need the *'s and &'s.


Solution

  • The problem is your use of the range-based for loop. It iterates over the values in the container, not giving you indexes into the vector.

    So in the loop i is the values from the vector.