简体   繁体   中英

converting vector iterator to pointer

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.

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)
}

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM