我需要计算给定字符串中每个字符出现的次数。我需要在 C 或 C++ 上完成,我可以使用任何库。问题是我不是 C/C++ 开发人员,所以我不确定我的代码是否最优。我想得到最好的性能算法,这是这个问题的主要原因。
我目前正在使用以下代码:
using namespace std;
...
char* text; // some text, may be very long
int text_length; // I know this value, if it can help
map<char,int> table;
map<char,int>::iterator it;
for(int i = 0; c = text[i]; i++) {
it = table.find(c);
if (it2 == table.end()) {
table[c] = 1;
} else {
table[c]++;
}
}
我可以使用除 std::map 之外的任何其他结构,但我不知道哪种结构更好。
谢谢你的帮助!