¿Optimizando la búsqueda de la cadena más ancha en una matriz de cadenas?

Right now I have an array of std::strings, and have a function in my font to find how wide it is.

 for(std::vector<std::pair<std::string,bool>>::const_iterator it = items.begin();
  it != items.end(); ++it)
  cSz = getFont().getTextWidth(it->first);
  if( cSz > h)
   h = cSz;
 widestItem = h;

I was wondering if I was possibly overlooking a better way to do this since this is a very brute-force way to find it.

In my situation there wouldn't be much point in storing the width of each one and referring to that.

Muchas Gracias

preguntado el 09 de enero de 11 a las 04:01

2 Respuestas

If I were optimizing this I'd:

  1. Make sure to use a profiler to find out that this is where significant time is going.

  2. Maybe have a cache of (font, string) tuples. If you're repeatedly computing the width of the same strings, this will help. But it depends on your exact use case.

  3. You can make your getTextWidth method very fast in the common case - you can have a flat array of 256 text-width units, and just dereference and sum up for each latin-1 character you've got. That'll be fast enough that you won't see the time spent on a modern CPU. Of course, you still have to implement non-Latin characters, and you may or may not want to do kerning, ligatures, and complex text layout (which is where this stuff can get expensive).

Respondido el 09 de enero de 11 a las 07:01

If string length is important you could store the length of it when adding the string to the vector, that way you wouldn't need to compute it every time (you could use a std::tuple of 3 items instead of std::pair if you have access to C++0x). If you change fonts often then that may not be suitable. Or you could store the length and recompute the lengths when changing fonts if the vector doesn't contain millions of items.

Optimization is hard when we don't have much information on the structure of the software and what you are doing apart from this small snippet.

Respondido el 09 de enero de 11 a las 07:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.