这是我的问题。我在游戏中为Gui创建了一个TextBox。
它的作用是,每次我调整它的大小时,因为它都是自动换行的,所以我必须弄清楚插入符号在文本字符串中位于哪个索引,然后需要在调整大小后将其转换为正确的行列。根据我的探查器,最慢的部分是当我获得下一个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关于字符的双尾队列是什么意思?
最佳答案
您正在提取具有以下内容的子字符串:
curChar = getText().substr(bytesSkipped,curCharLen);
但是,您仅使用第一个元素。您只需提取所需的
char
即可避免字符串构造/复制。在常规算法优化上-我将花费构建字符对象的
deque
所需的资源,而不是使用std::string
。这将使您直接索引任何字符,而无需一遍又一遍地扫描和解析相同的utf-8序列。关于c++ - 帮助优化此索引到行列,反之亦然,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5320057/