Adding a "sorted insert" method to std::list

I need a std::list but I need its contents sorted upon insertion.
First thing that comes to mind is deriving a class from std::list and then just adding the desired method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <list>
using namespace std;

template<class T>
class mylist: public list<T>{
public:
	list<T>::iterator insert_sort(const value_type &val){
		list<T>::iterator it;
		for(it = begin(); it != end(); it++){
			if(val < *it){
				break;
			}
		}
		return insert(it, val);
	}
};
However I get error messages:
test.cpp:7:2: error: need 'typename' before 'std::list<T>::iterator' because 'std::list<T>' is a dependent scope
  list<T>::iterator insert_sort(const value_type &val){
  ^
I have no idea what this means, can someone help me out?
the message means exactly what it says, the correct syntax is typename list<T>::iterator because T is a dependent type

but there are problems with deriving from std::list: Imagine a user took a reference or a pointer to your list, assumed it is std::list (public inheritance claims that your list IS-A std::list) and did things to it that are expected of std::list? The user might break your sorted order or might attempt to delete the list (in more technical words, your design violates LSP and derives from a class without a virtual destructor)

Consider composition over inheritance: make std::list a member of your class. Or just write a non-member function.
Last edited on
Thanks, I've just never seen that syntax before.

I'm not exactly sure what you're talking about as far as the drawbacks of using a derived class. For me as a beginner it saves typing.
Last edited on
Topic archived. No new replies allowed.