Pointer to List Iterator As Function Argument
Hi,
I've written a simple program which involves a class called person, and a list of person objects to represent a list of people. Each person object just has a name and an ID at present. To read stuff from the list of person objects I'm using an iterator.
I figured it would make sense to write a set_iter function that takes a pointer as an argument, so that I could set the iterator to refer to a particular person object with a certain ID, without having to do something like:
Code:
iter = personlist.begin()
while (iter != 2)
iter++;
So that's what I've done, by having a buffer iterator in the set_iter function, which effectively does what that code above does whenever you type set_iter(&iter, 2). My first question is:
1. Is the way I've written set_iter an efficient way to do it? Or is there a better way of writing it? Maybe one that doesn't require the buffer iterator to be declared?
Also, a couple of minor questions, if anyone has time:
2. Do you say that the set_iter function has a pointer as an argument, or an address as an argument? Because it has a pointer in the definition but you actually pass an argument.
3. Is a list a good choice of container here or would a vector be better? If so, how come?
Thanks guys.
Code:
#include <iostream>
#include <list>
#include <string>
using namespace std;
class person
{
private:
string name;
int id;
public:
person(const string& nm, int i) {name = nm; id = i;};
int getid() { return id; };
string getname() { return name; };
};
list<person> personlist;
list<person>::iterator iter;
void set_iter(list<person>::iterator *target_iter, int target_id);
int main()
{
personlist.push_back(person("Arnold", 0));
personlist.push_back(person("Barry", 1));
personlist.push_back(person("Colin", 2));
set_iter(&iter, 2);
cout << "name of person with id 2 = " << iter->getname() << endl;
}
void set_iter(list<person>::iterator *target_iter, int target_id)
{
list<person>::iterator buffer_iter = *target_iter;
buffer_iter = personlist.begin();
while (buffer_iter->getid() != target_id)
buffer_iter++;
*target_iter = buffer_iter;
}