1

I am trying to implement Python's list.pop method in C++. The method takes an index as argument, defaulting to the last index. Here is an example.

The only way I see to achieve this is to involve the list's size in the default value of the parameter, but that cannot be determined at compile time and so is not a valid default value in C++.

How can I pass the argument as desired?

Community
  • 1
  • 1
wsaleem
  • 594
  • 8
  • 25

1 Answers1

1

This is a situation in which I think that rather than a default argument value, you should just use two methods:

void pop() { removeNode(tail); }
void pop(std::size_t idx) { removeNode(getNode(idx)); }

If you try to do it with one method, you're going to have to decide on a certain 'special' value, and though that will realistically work (e.g. the max value of the type if you use an unsigned type, or -1 if you use a signed one), it's not really semantic, and it could even cause bugs. For example, some bad math could end up passing in -1. It'd be much better for that to error in some way rather than to just pop the last element.

This does, of course, assume that you're keeping a tail pointer, but if you're planning on popping the last element, you should have a tail pointer anyway. C++ tends to take an approach of only defining operations on data type if they're efficient, and a linear tail-pop on a linked list is far from the efficiency people would expect if the method is provided.


By the way, if you're trying to make a robust implementation (though hopefully you'd just use the standard library's list), you should consider iterators. Not only are they more native to C++, they actually have a performance advantage here. Removing an index from a list is a linear time operation. Removing an iterator is easily implementable in constant time. The usage between an index and an iterator is of course different since indexes can be used to move across more than 1 element at a time, but I'd argue that if you can't pleasantly use only the ability to move forward by one element or backward by one element to do whatever you're trying to do with a list, you're using the wrong data structure anyway. Using indexes with a linked list tends to devolve into treating it like a container that can perform random access quickly, when in reality it is very, very far from that.

Corbin
  • 33,060
  • 6
  • 68
  • 78
  • As mentioned, using indexes with a linear structure is semantically bad. This is not meant to be commercial, robust code, rather it is part of an academic exercise. – wsaleem Dec 05 '15 at 07:57