returning c++ iterators

c++, iterator, vector

Solution

Don't return an iterator to a hidden container. Return simply what it is that you want, namely a means to access an object if it exists. In this example, I store the objects in the container via pointer. If your objects only exist temporarily, then new one up and copy the object over!

class AClass;

//...some time later
std::vector<AClass*> vecCont; //notice, store pointers in this example!

//..some time later
AClass * findAClass(int id, int test)
{
  vector<AClass*>::iterator it;

  for(it = class.vecCont.begin(); it != class.vecCont.end(); ++it)
  {
     if(found object) //currently in psuedo code
     return it;
  }

  return NULL;
}

//later still..

AClass *foundVal = findAClass(1, 0);
if(foundVal)
{
  //we found it!
}
else
{
  //we didn't find it
}

edit: the intelligent thing to do is to write a comparator for your class and use the std algorithms sort and to find them for you. However, do what you want.

Problem

I have a function that returns an iterator if an object is found. Now i have a problem. How do i fix the problem of informing the object that called this function that the object was not found? ``` vector<obj>::iterator Find(int id, int test) { vector<obj>::iterator it; aClass class; for(it = class.vecCont.begin(); it != class.vecCont.end(); ++it) { if(found object) //currently in psuedo code return it; } return ???? // <<< if not found what to insert here? } ``` Do i need to change my data structure in this instead? Thanks in advance! :)

Original source