CUtlMap
Jump to navigation
Jump to search
CUtlMap
is Source's equivalent of the C++ Map type. A map is essentially a dynamic length array where each iterator, or member,
is mapped to a specific, unique key value. The code can be found in public/tier1/utlmap.h
.
Finding bounds
Count()
- The total number of items in the map.
IsValidIndex( int i )
- Self-explanatory.
InvalidIndex( )
- Returns an invalid index.
EnsureCapacity( int num )
- Makes sure we have enough memory allocated to store a requested number of elements.
Adding elements
Insert( const KeyType_t &key, const ElemType_t &insert )
- Inserts the element and key into the tail of the map.
InsertOrReplace( ( const KeyType_t &key, const ElemType_t &insert )
- Inserts the element and key into the tail of the map, replacing the element if the key is the same as one that already exists
Reinsert( const KeyType_t &key, IndexType_t i )
- Replaces the element at index i with the element that has the given key.

To specify the LessFunc for your map, use SetDefLessFunc(mapList)
.
Accessing Elements
You can use array-style or use a method for index access:
Element( IndexType_t i )
operator[]
- Gets a pointer to CBaseEntity

CUtlMap
's accessor functions do not find a specific iterator by key, but rather, by index. Discrepancies
In std::map accessor functions will find an iterator by key., CUtlMap
's accessor functions do not find a specific iterator by key, but rather, by index.
This means that the following code
// Initialize map for given type
CUtlMap<int, CBaseEntity*> mapList;
// (Populate map here)
mapList.Insert(CBaseEntity->entindex(), CBaseEntity);
// Access map
mapList[ 3 ]->entindex();
mapList.Element( 3 )->entindex();
will return a pointer to CBaseEntity at index position 3
of the map, instead of the CBaseEntity that has key of 3.
In order to access the iterator at a specific key, use
//Find the index of our key value
int idx = mapList.Find(pBlock->entindex());
//Ensure that it is a valid index
if (mapList.IsValidIndex(idx))
{
CBaseEntity *pOther = mapList.Element(idx);
}