converting vector iterator to pointer

17,527

Solution 1

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

Solution 2

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

Solution 3

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;
}
Share:
17,527
Dr. Debasish Jana
Author by

Dr. Debasish Jana

SOreadytohelp More than Twenty-eight years of extensive industry experience in various stages of the software development life cycle. Specifically, involved in project management, software development, software maintenance, and teaching in India and abroad. Well versed with Software Life Cycle and OOAD techniques. Well conversant with software quality process and project execution methodology. Adopted special skills in object-oriented methodology, front-end tool development, mobile application development, enterprise software development as well entire software lifecycle process management. Taught at premier educational institutions in India and abroad. Authored three popular books on C++, Java and Computer Graphics published by PHI Learning. Authored many research papers in peer reviewed national and international conferences and journals. Performed role of Honorary Editor of CSI Communications, monthly technical magazine for CSI members (April 2011 to March 2015). Actively involved in several national and international conferences including EAIT 2006, CSI-2006, CSI-RDHS 2008, EAIT 2011, ReTIS-11, EAIT 2012, CSI-2012, EAIT 2014, ReTIS-15 as spearheading role in Program Committee and Editorial role in the Proceedings. Fellow - IE(I), IETE and Senior Member - IEEE, ACM. Also, Ex-Senior Life member, CSI.

Updated on June 04, 2022

Comments

  • Dr. Debasish Jana
    Dr. Debasish Jana almost 2 years

    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.

  • The Paramagnetic Croissant
    The Paramagnetic Croissant almost 8 years
    You don't need those parentheses, prefix operators are parsed left-to-right. &(*it) is the same as &*it.
  • NathanOliver
    NathanOliver almost 8 years
    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.