If you use only std::list(or std::vector, for that matter) you are not going to conduct a linear search, if you do not want to avoid duplication, but you want to keep the original order. It just
std::vectormight be:
int
createIndex( std::vector<T>& references, T const& newValue )
{
int results = std::find( references.begin(), references.end(), newValue )
- references.begin();
if ( results == references.size() ) {
references.push_back( newValue );
}
return results;
}
Alternatively you can use std::map:
int
createIndex( std::map<T, int>& references, T const& newValue )
{
st::map<T, int>::iterator results = references.find( newValue );
if ( results == references.end() ) {
results = references.insert(
std::make_pair( newValue, references.size() ) ).first;
}
return results->second;
}
(This assumes that it Tsupports <. If not, you will need to set custom criteria. Or use unordered_mapand define a hash code for it.)
source
share