Access an object stored in the list.
Hi all,
I am storing some objects in the list and the i am trying to access them one by one. Each object consists of two strings and one integer.
The problem is that i cannot access these objects through the iterator.
1.How can i access these objects?
Code:
#include <stdlib.h>
#include <iostream>
#include <map>
#include <list>
using namespace std;
class A{
public:
string x;
string y;
int z;
};
list<A> G_QUERY_LIST;
list<A>::iterator it;
void create_new_query()
{
string name;
string query;
string results;
cout << "Please enter a name for this query: ";
cin >> name;
cout << "Please enter the query you want to execute: ";
cin >> query;
A ena;
ena.x = name;
ena.y = query;
G_QUERY_LIST.push_back(ena);
}
int main() {
create_new_query();
create_new_query();
cout << "mylist contains:";
for (it=G_QUERY_LIST.begin(); it!=G_QUERY_LIST.end(); it++)
cout<< *it.ena.x;
cout << endl;
return 0;
}
Many thanks in advance.
Re: Access an object stored in the list.
Code:
for (it=G_QUERY_LIST.begin(); it!=G_QUERY_LIST.end(); ++it)
cout<< (*it).ena.x;
Priority of * is lower than that of "."
FYI: Note that, generally, ++it is faster for iterators.
HTH
PS: If you do not mind using 3rd party libs: using Boost.Foreach your code could be written
Code:
#include <boost/foreach.hpp>
BOOST_FOREACH(const A &item, G_QUERY_LIST)
cout<< item.ena.x;
Re: Access an object stored in the list.
Excellent answer thats what i wanted!
A small correction:
its (*it).x and not (*it).ena.x