Search code examples
c++vectorargmax

c++ finding argmax of vector from specific indices


from here, i know that we can get the argmax of a `vector like this:

vector<int> v{ 3, 1, -14, 1, 5, 9 }; 
vector<int>::iterator result = max_element(v.begin(), v.end());
int argmaxVal = distance(v.begin(), result);
// argmaxVal = 5 because v[5] = 9

How do i get the argmax of vector from index 2 to 4? Or, in general, from index k to index n, (assumed to be contiguous).

// argmaxVal = 4 because v[4] = 5
// which is max of v[2], v[3], v[4]

Obviously i can do it like this:

int VectorArgMax(vector<> v, int start_idx, int end_idx){
    int retVal = start_idx;
    for (int idx=start_idx; idx<=end_idx; idx++){
        if v[idx] > v[retVal]{
            retVal = idx;
        }
    }
    return retVal;
}
result = VectorArgMax(v,2,4);

But is using max_element and distance faster, or any even faster function I can use directly?


Solution

  • You can simply adjust the input iterators to std::max_element:

    std::vector<int>::iterator max = max_element(v.begin() + 2, v.begin() + 4); // [2, 4)
    int argmaxVal = distance(v.begin(), max); // absolute index of max
    

    You can also replace std::vector<int>::iterator with auto for convenience with C++11.