Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting between pointers and references

std::list<Value> stdList;

stdList.push_back(Value());

Value * ptr = &stdList.back(); // <-- what will this address point to?

If I take the reference returned by back() and implicitly convert it to the less generic Value *, will it point to the last value of the list, or will it point to someplace unexpected?

And is there a way to create an iterator from a pointer, for use with std::list functions such as erase()? I realize generic to specific (iterator to pointer) is far more feasible than going the other direction, but I thought I'd ask anyway.

like image 812
Anne Quinn Avatar asked Jun 04 '26 10:06

Anne Quinn


1 Answers

The pointer will point to the value as it is stored inside the container. The reference did the same thing.

You can't turn that pointer into a list iterator directly, because you've lost all the information about the surrounding structure. To do this you would have to get clever with list::find.

What you are trying to do it is sometimes done using vector. The reason you can turn a vector data element pointer into an iterator (array index) is because you know the structure of a vector.

Please note that list::back() does not return an iterator. It returns a reference. The two are quite different. Are you thinking about list::end()? Or are you genuinely confused between iterators and references? Because you can get a reference from a pointer. You do it like this:

Value& refval = *ptr;
like image 117
paddy Avatar answered Jun 06 '26 01:06

paddy



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!