Iterator in lists

Hi,
I'm a beginner in using C++ so I apologize if I'm wrong with scientific definitions of something. I need a suggestion for a doubt related to classes. Let's suppose to have the class InfoElement defined below. This class has more lists/elements. In addition, let's suppose I have already inserted the values of each list of this class (n, KX, KY, KZ).
I want to read only the list KY. I know about the esistence of iterators but, according to my poor knowledge, iterators read the position and not what list (it is like in a hypotetic matrix iterators give the row number, not the column one).

How can I obtain a KY value in a certain position?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class InfoElement
{
private:
	long index_element_; 
	double n_;
	double KX_;
	double KY_;
	double KZ_;
	
public:
	PropertyElement();
	~PropertyElement();
	PropertyElement(long index_element, double n, double KX, double KY, double KZ); 
	long index_element();
	double n();
	double KX();
	double KY();
	double KZ();
	
};


Thank you for you help!
Err... What? A class is not a list. If I define a class like
1
2
3
4
5
6
class A{
     int item1;
     int item2;
     int item3;
     int item4;
};
item1 etc. are not elements of a list, they're members of a class. You can't iterate members of a class, the language doesn't work like that.

A list is something more like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct ListNode{
    int datum = 0;
    ListNode *next = nullptr;
};

ListNode *construct_list(){
    auto node = new ListNode;
    auto ret = node;
    node->datum = 1;
    node->next = new ListNode;

    node = node->next;
    node->datum = 2;
    node->next = new ListNode;

    node = node->next;
    node->datum = 3;
    node->next = new ListNode;

    node = node->next;
    node->datum = 4;
    
    return ret;
}
Notice how a) all the items of the list have the same type (i.e. they're homogeneous) and b) the list has arbitrary length that's defined at run time. Iterators are used to traverse homogeneously-typed collections (data structures) of arbitrary lengths.

One final thing I'll say is that, although C++ doesn't support iterating classes, some other languages do support that, through a feature known as "reflection".
The items in a class are called members. You can access them using the . operator:
1
2
3
InfoElement item;    // create an InfoElement called "item"
double sum = item.KX() + item.KY();   // add the KX and KY members of "item", store the result in "sum"
cout << "KX + KY = " << sum << '\n';  // print out "sum" 
Topic archived. No new replies allowed.