If you re using just a std::list
(or std::vector
, for that matter),
you re not going to get around a linear search if you don t want to
avoid duplicated, but you want to keep the original order. A simple
std::vector
based solution might 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;
}
或者,你可以使用<代码>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 supposes that T
supports <
. If not, you ll have to establish
an ordering critera. Or use unordered_map
and define a hash code for
it.)