I called my template OrderedList
, but I don't like the name. Is there a better one?
It stores a vector of values of type T
, and a map
from each value to its index in the vector.
Just for information, the code should be pure C++03, so please don't suggest how it could be improved with C++11/14/17 extensions, or with Boost.
template<class T> class OrderedList {
public:
typedef typename std::map<T, int> MapInd;
public:
int Insert(const T& val); // insert new value, return its index
int Find(const T& val) const; // find index for the value, or -1 if not found
const T& operator[](int i) const {return vValues[i];}
int Size() const {return vValues.size();}
private:
MapInd mapIndices; // index for each element
std::vector<T> vValues; // element for each index
};
template<class T> int OrderedList<T>::Insert(const T& val) {
if (Size() < 0)
return -1;
int ind = Find(val);
if (ind >= 0)
return ind;
ind = Size();
mapIndices[val] = ind;
vValues.push_back(val);
return ind;
}
template<class T> int OrderedList<T>::Find(const T& val) const {
typename MapInd::const_iterator it = mapIndices.find(val);
if (it != mapIndices.end())
return it->second;
return -1;
}
SortedList
? \$\endgroup\$