From Valve Developer Community
Revision as of 22:15, 2 March 2011 by TomEdwards (talk | contribs) (cleased/wikified)

Jump to: navigation, search

CUtlSortVector is a CUtlVector that automatically orders its elements using binary search. Code can be found in public/tier1/utlsortvector.h.

Warning: Vector elements are moved around in memory, so never use pointers to them. Warning: CUtlSortVector is not thread-safe under Linux.


A CUtlSortVector expects a type and a sorting class. Here is an example:

// Sorting class
class CEntityReportLess
	bool Less( const CBaseEntity &src1, const CBaseEntity &src2, void *pCtx )
		return stricmp( src1->GetClassname(), src2->GetClassname() ) < 0;

CUtlSortVector<CBaseEntity*, CEntityReportLess> sortedList;

The CUtlSortVector will then use the Less method to determine the order of elements. Note how the function has a third argument for a sorting context (see below).

Adding elements

Only Insert( const T& src ) or InsertNoSort( const T& src ) is allowed when adding elements to a CUtlSortVector. InsertNoSort( const T& src ) just puts the element at the tail of the vector. Warning: When using InsertNoSort, you are only allowed to use that particular index until sorting is redone, or you will get a fatal Assert!

Sorting context

Using SetLessContext( void *pCtx ), you can set a sorting context that will be passed to the Less function. To do: What is a sorting context?


CUtlSortVector uses binary searches to find elements, which are very fast.

Find( const T& src )
Searches through the CUtlVector and returns the element index, or -1 if the given object was not found.
FindLessOrEqual( const T& src )
FindLess( const T& src )
As above, but also considers elements that rank lower than the given object.

Single elements

Remove( const T& search )
Searches for the element using Find() and removes it from the vector.
Remove( int i )
Removes the element at the specified index.


With RedoSort( bool bForceSort = false ), the CUtlSortVector is resorted using QuickSort. Use bForceSort to sort regardless if it is necessary or not (it becomes necessary when you use the InsertNoSort method).