Accessing data of list in a vector??

Hi I'm new to c++ and I'm trying to print out the data (x_data) in a list, in which the list is part of a vector. I just can't seem to access the data in the list correctly. I'm sure its not too difficult for most of you here, but I can't seem to get it! thanks in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <iostream>
#include <vector>
#include <list>
#include <time.h>

using namespace std;

struct l_node
{
        int x_data;
        int y_data;
};

struct v_node
{
        int h_data;
        list<l_node> v_list;
};

int main()
{
        vector<v_node> v(10);
        int i, n = v.size();
        for(i=0;i<10;i++)
        {
           v_node vnode;
           vnode.h_data = i;
           for(int j=0;j<10;j++)
           {
                l_node lnode;
                lnode.x_data = j;
                lnode.y_data = int(rand()*10);
                vnode.v_list.push_front(lnode);
           }
           v[i] = vnode;
        }
		for(i = 0; i < n; i++)
              l_node lnode;
		      cout<<v[i].h_data<<" "<<v[i].v_list.x_data<<"\n"; //can't print x_data's value
        cout << "endl";		
        system("PAUSE");
}
Last edited on
v[i].v_list is an STL list itself - you'll need an iterator (list<l_node>::iterator) to access and/or iterate it. Try something like

1
2
3
4
for(int i=0; i<n; +++)
{
  for(list<l_node>::iterator ix = v[i].v_list.begin(); ix != v[i].v_list.end(); ++ix)    cout << v[i].h_data << " " << (*ix).x_data << "\n"
}


Check out the STL section on cplusplus.com if this makes no sense

HTH,

/Troels
thanks! that worked and made sense!
Last edited on
Topic archived. No new replies allowed.