mercredi 5 avril 2017

Fast 'group by/count' std::vector

I have a function that reads ~10000 words into a vector, I then want to group all the words into a map to 'count' how many times a certain word appears.

While the code 'works' it can sometimes take 2 seconds to re-build the map.

NB: Unfortunately, I cannot change the 'read' function, I have to work with the vector of std::u16string.

std::vector<std::u16string> vValues;
vValues.push_back( ... )
...

std::map<std::u16string, int> mValues;
for( auto it = vValues.begin(); it != vValues.end(); ++it )
{
  if( mValues.find( *it ) == mValues.end() )
  {
    mValues[*it] = 1;
  }
  else
  {
    ++mValues[*it];
  }
}

How could I speed up the 'group by' while keeping track of the number of times the word appears in the vector?

Aucun commentaire:

Enregistrer un commentaire