I am writing a simple program.. enter first and last name and a search is performed.. and their phone number (if found) is returned.
I have used vector class iterators before a couple of times.. but devcpp does not seem to like this code.. and stops compilation somewhere inside of the algorithm find() function.
The function searches through a vector of "info"'s in an attempt to match the first name. If successful, the last name is checked. If the the last name does not match, the search continues.. else 'iter' will point to the vector element containing the matching first and last target name.
The entire code has been uploaded for your viewing pleasure. Any help is appreciated in advance.
I'm gonna say iter isn't valid. Don't worry, I'll explain my thought process. But bear with me because it's twisted. :D You initialize iter in the Database constructor.
Technically you don't need to clear vInfo because it's freshly created, but that doesn't really matter. The problem is that you initialize iter to vInfo.begin() here, before inserting any data. Then you go to call load_file. Skipping the boring stuff, the problem's here.
vInfo.push_back(temp);
vInfo.push_back(temp) is like calling vInfo.insert(vInfo.end(), temp) , and if a call to insert for a sequence container reallocates memory, all iterators are invalidated. Since vInfo was both empty and freshly constructed with no resize or reserve, push_back invalidates iter. Then you try to use an invalid iterator in find.
iter = find(iter++, vInfo.end(), target_firstname);
If you move the iter = vInfo.begin() to the top of your search method, I'm guessing it'll work. Or at least crash differently. :)
If you're going to use std::find like that, you need to define an equality operator for your info class:
class Info
{
public:
bool operator==(const std::string& first_name);
//...
}
However, you may want to use std::find_if instead. find_if allows you to specify an unary predicate as the matching criteria, so you could do something like (assuming my logic here is correct, since this is untested):