I have a simple question about pointers in a list.
pointer* Temp2;
Temp->data = 10; //(Temp is one of the elements in a list)
//Now I want to use a pointer to point at this element in order to modify its data.
Temp2=Temp;
Temp2->data = 5;
Will this do the job?
As long as it's not a local pointer, yes, and only because it's a list. If it was a vector for example, the answer would be no, since your pointer would probably point to another element as soon as you modified the vector, while that doesn't happen with a list.
what i mean by local pointer is
_DATA local_data;
pointer *local_p = &local_data;
list.push_back(local_data);
local_p is useless now because it's pointing to the stack, and you need to get a pointer to the heap, which std::list has created for your new element.
for example
pointer *improved_pointer = &*list.begin();
now you can do
pointer *alias = improved_pointer;
and of course, both pointers will work, until you delete the element from your list container, only then it would invalidate your pointers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.