Qioda
Qioda

Reputation: 11

C++: Difference between std::list<type*> and std::list<*type>

Im currently learning C++ and I have seen an iterator doing the following:

for(std::list<Type*>::iterator iter = list.begin();
 iter != list.end(); ++iter) {

 if (!isInRange(**iter)) {
 iter = list.erase(**iter);
 }
}

Now, my question is: How do I know whether a double pointer is used or not? To get the object of iter, the solution uses two **, but the declaration of the iterator defines the type as a single pointer, not double pointer: <Type*>. Is there a difference between std::list<Type*> and std::list<*Type>? If a * on the right side of the type means, that it is a double pointer, then I would understand why I would need to use two ** in order to get the object.

Thank you very much in advance! Qioda

Upvotes: 0

Views: 121

Answers (1)

MarcMDE
MarcMDE

Reputation: 23

Focusing on your main question:

How do I know whether a double pointer is used or not

You are creating a list storing pointers of type Type (Type*), and you are using a std:list<T>:iterator in order to iterate over this list.

An iterator basically references to a node of the list. It is, "by definition", a pointer.

The values you are storing in your list are pointers of type Type (Type*). And you are referencing a value (Type*) using an iterator.

  • The variable iter is your iterator. It references a value on your list (Type*).
  • The instruction *iter will return a Type* (pointer of type Type).
  • The instruction **iter will return a Type (value of type Type).

Summing up, you always need to use *iter to obtain the value referenced by the iterator. You need **iter if you created a list storing pointers and you want to obtain the value referenced by the pointer stored in your list.

About the last line of the code you provided iter = list.erase(**iter) you have to use iter instead of **iter, because the erase method requires an iterator as a parameter, not a Type.

Finally, if you create a list of Type instead of a list of Type*, *iter would return a value of type Type.

Please, try to formulate your questions in a clearer way.

Upvotes: 1

Related Questions