Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

range based for loop for custom linked list containing pointers in C++, only returns objects

We wrote a custom container class that should be able to support rang based for loop, see here: c++ shell. When you run the example you can see that it is working.

Essentially the container is a linked list of pointers to Elements:

    LinkedList ll;
    ll.push_back(new Element(1));
    ll.push_back(new Element(2));
    ll.push_back(new Element(3));

    for(LinkedList::iterator it = ll.begin(); it != ll.end(); ++it){
        cout << it->some_value << endl;
    }

    for(Element ele : ll) {
        cout << ele.some_value << endl;
    }

will print123123. What we don't understand is: Why are the ele in the range based for loop not pointers? Or better why does this not work:

for(Element * ele : ll) {
    cout << ele->some_value << endl;
}

Basically we want to achieve the same with the custom linked list as can be achieved with the std vector:

vector<Element*> vec{new Element(1),new Element(2),new Element(3)};
for(Element * ele : vec)
{
    cout<<ele->some_value<<endl;
}
like image 323
newandlost Avatar asked Nov 21 '25 05:11

newandlost


1 Answers

The standard defines the ranged based for to be equivalent to:

{
  auto && __range = range-init;
  for ( auto __begin = begin-expr,
             __end = end-expr;
        __begin != __end;
        ++__begin )
  {
    for-range-declaration = *__begin;
    statement
  }
}

The reason ele shouldn't be a pointer is because of the dereference of the iterator (for-range-declaration = *__begin;), so the for-range-declaration needs to be a reference type or the actual value type.

Hence you need to change your iterator class such that the operator* returns Element* or Element*&.

like image 198
Nullrelation Avatar answered Nov 22 '25 19:11

Nullrelation



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!