12

I have a vector std::vector. I would like to iterate the vector for finding a match, if found would like to return the pointer to the element as below:

const int * findint(std::vector <int> &v, int a)
{
        std::vector<int>::const_iterator i1,i2;
        i1 = v.begin();
        i2 = v.end();
        for(;i1 != i2;++i1) {
                if(a== *i1) {
                        return(i1);
                }
        }
        return(0);
}

This was compiling and working ok with GNU g++2.95.3 compiler but not compiling with GNU g++ 4.9.2 and giving the following error:

error: cannot convert 'std::vector<GenFld>::const_iterator {aka __gnu_cxx::__normal_iterator<const int*, std::vector<int> >}' to 'const int*' in return
     [exec]     return(i1);

Need help.

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69

3 Answers3

22

This will solve your problem:

const int * findint(const std::vector <int> &v, int a){
    auto i1 = v.cbegin();
    auto i2 = v.cend();
    for(;i1 != i2;++i1){
        if(a == *i1){
            return &*i1;
        }
    }
    return nullptr;
}

Edit: Note that I changed iterators to cbegin and cend also the vector is now passed as const.

However, the right way to do it IMO (with respect to nathanoliver note):

auto it = std::find(v.cbegin(),v.cend(),value);
decltype(&*it) ptr;
if(it==v.cend()){
    ptr = nullptr;
}
else{
    ptr = &*it;
}

You have to be careful when using this. Pointers and Iterators may be invalid after any push_back or insert or erase on the vector, for a comprehensive list see Iterator invalidation rules. If you want to keep a clue to reach some item later. and if you can guarantee that only adding to the back of the vector will happen, you may keep the index of the item using:

auto it = std::find(v.cbegin(),v.cend(),value);
size_t index;;
if(it==v.cend()){
    //do something
}
else{
   index = std::distance(v.cbegin(),it)
}
Community
  • 1
  • 1
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
  • You don't need those parentheses, prefix operators are parsed left-to-right. `&(*it)` is the same as `&*it`. – The Paramagnetic Croissant May 20 '16 at 12:03
  • 2
    If there is no element in the vector this will convert the end iterator to a pointer. There is no guarantee that it will point to one past the end of the vector storage. The function should check for this and return `nullptr` if no element is found. – NathanOliver May 20 '16 at 12:13
3

Use v.data():

const int * findint(const std::vector <int> &v, int a)
{
  const int * const b = v.data();
  const int * const e = b + v.size();
  const int * const r = std::find(b, e, a);
  return (r == e) ? nullptr : r;
}
filipos
  • 645
  • 6
  • 12
1

You could do something like this

auto i1 = std::find(v.begin(), v.end(), a);
if(i1 != v.end())
{
    index = std::distance(v.begin(), i1); 
    return(&v[index])
}
else
{
    return NULL;
}
thorsan
  • 1,034
  • 8
  • 19