Search code examples
c++constants

Why does "int *find(const vector<int> &vec, int value)" give me an invalid conversion error?


I am new to C++ and trying to play with some examples in book "Essential C++". When I write this code from the book:

int *find(const vector<int> &vec, int value) { ... }

The g++ compiler gives me an error:

error: invalid conversion from 'const int*' to 'int *' [-fpermissive]

I try to change it to

const int *find(const vector<int> &vec, int value)

and it works fine.

So I am just wondering is there any detail reason for this? Thanks!

Here is the code from the book:

int* find(const vector<int> &vec, int value) {
     for(int ix = 0; ix < vec.size(); ++ix)
     {
         if(vec[ix] == value) 
         return &vec[ix];
     }
     return 0;
 }

Solution

  • I am guessing you are doing something like

    int *find(const vector<int> &vec, int value) 
    { 
      ... 
      return &vec[someIndex];
    }
    

    You cannot do that, since you are passing a const reference to the vector. Hence the need to return const int*.

    What you really should do it use std::find.

    vector<int>::const_iterator i = std::find(vec.begin(), vec.end(), value);
    
    // check if an element was found and print it out
    if (i != vec.end()) std::cout << *i << std::endl;
    

    This has the added advantage that it does not produce undefined behaviour when a value is not found in the vector.