帮助优化此索引到行列,反之亦然算法

时间:2011-03-16 01:34:17

标签: c++ algorithm optimization

这是我的问题。我在游戏中为我的Gui制作了一个TextBox。

它的作用是,每当我调整它的大小时,因为它包装了文字,我必须弄清楚文本字符串中插入符号所在的索引,然后我需要在reize之后将其转换为正确的行列。根据我的分析器最慢的部分是当我得到下一个要评估的unicode字符时:

int AguiTextBox::indexFromColumnRow( int column, int row, bool includeUnwantedChars ) const
    {
        size_t rowLen = 0;

        int retIndex = -1;
        int bytesSkipped = 0;
        int curCharLen = 0;
        std::string curChar;

        std::string::const_iterator it = getText().begin();
        std::string::const_iterator end = getText().end();


        //decrement column so that the lowest is -1
        column--;
        if(textRows.size() == 0 || (column == -1 && row == 0))
        {
            //not in the text
            return -1;
        }
0.01s       for(size_t i = 0; i < textRows.size(); ++i)
        {
            //get length of row
0.00s           rowLen = _unicodeFunctions.getUtf8StringLength(textRows[i]);

            //handle -1th case

            //get next character
            do 
            {
0.00s               curCharLen = _unicodeFunctions.bringToNextUnichar(it,end);
0.01s               curChar = getText().substr(bytesSkipped,curCharLen);
                bytesSkipped += curCharLen;
                if(includeUnwantedChars)
                    retIndex++;
            } while (curChar[0] >= 0 && curChar[0] < ' ' && curChar != "\n");

            if(!includeUnwantedChars)
            retIndex++;

            //only increase for newlines
0.00s           if(curChar != "\n")
            {
                bytesSkipped -= curCharLen;
                retIndex--;
                it -= curCharLen;
            }

            if((int)i == row && column == -1)
            {
                return retIndex;
            }


0.06s           for(size_t j = 0; j < rowLen; ++j)
            {
                //get next character
                do 
                {
0.10s                   curCharLen = _unicodeFunctions.bringToNextUnichar(it,end);
0.91s                   curChar = getText().substr(bytesSkipped,curCharLen);
0.03s                   bytesSkipped += curCharLen;

0.03s                   if(includeUnwantedChars)
                        retIndex++;

0.11s               } while (curChar[0] >= 0 && curChar[0] < ' ' && curChar != "\n");

0.06s               if(!includeUnwantedChars)
0.00s                   retIndex++;

0.02s               if((int)i == row && (int)j == column)
                {
                    return retIndex;
                }
            }
        }

        return retIndex;
    }

我该如何优化呢?

由于

@Erik对字符的双端队列意味着什么?

1 个答案:

答案 0 :(得分:1)

您正在使用以下内容提取子字符串:

curChar = getText().substr(bytesSkipped,curCharLen);

但是你只使用第一个元素。您只需提取所需的char即可避免字符串构造/复制。

在一般算法优化方面 - 我将花费构建deque个角色对象所需的资源,而不是使用std::string。这将允许您直接索引任何字符,无需一遍又一遍地扫描和解析相同的utf-8序列。