0

I have an the error "cannot have a cv qualifier" for the function indice_max and I don't understand why, I don't modify at any time the vector v

#include <iostream>
#include <vector>
#include <algorithm>

using std::vector;

int indice_max(const vector<double> & v) const{
    int indice =0;
    double max = v[0];
    for(int i=0; i<v.size(); i++){
        if(v[i]>max){
            max = v[i];
            indice = i;
        }
    }
    return indice;
}
  • You can't declare a non-member function as `const`. – songyuanyao Aug 11 '20 at 09:14
  • `int indice_max(const vector & v) const` the second `const` declares that the class of which this is a member function of has its variables logically constant for this function. If this is _not_ a member function than that makes no sense. Hence you cant declare non member functions as `const`. – Mike Vine Aug 11 '20 at 09:15
  • This might answer your question: https://stackoverflow.com/questions/3474119/const-type-qualifier-soon-after-the-function-name – jignatius Aug 11 '20 at 09:31

1 Answers1

0

The const qualifier (after the function signature) is used when the class member-function promises not to change any previously assigned value to a data member.

In the given code, there's no class and its private data members. Thus, there's no meaning of using it in this case and a type qualifier isn't allowed on a nonmember function.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34