Find the answer to your Linux question:
Results 1 to 4 of 4
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. ...
  1. #1
    Just Joined!
    Join Date
    Sep 2007
    Posts
    33

    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.

  2. #2
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    I'm no expert on C++ but if your going to push a class A onto a list you have to do it either by passing a reference to it(which you can't do here because your class is create as a automatic variable i.e in a function) or you need to copy your class onto the list which you can't do here because your class has no copy constructor but like I said I'm no expert in C++

  3. #3
    Just Joined!
    Join Date
    Sep 2007
    Posts
    33
    Many thanks for the reply friend i think i found the error:

    it is (*it).x;

    because of the dot we need to put some parenthesis.

    Regards

  4. #4
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    try it->x its easier to understand than (*it).x and you really should have a defined constructor/destructors in your class...its easier to understand your intention when your code is spelled out in stead of using the defaults

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...