简体   繁体   English

为了保证单个字符,使用`char`或`string`更好吗?

[英]For a guaranteed single character, is it better to use `char` or `string`?

I have a variable that's guaranteed to be a single character (substr from a std::string ). 我有一个保证是单个字符的变量(从std::string代替)。

I strongly suspect that it's more efficient to use a char , ie 我强烈怀疑使用char更有效,即

char c = name.c_str()[offset];

instead of the more complicated (and costly) 而不是比较复杂(和昂贵)

std::string c = name.substr(offset, 1);

I'm not going to do any intensive operations on the resulting character (just one switch statement). 我不会对生成的字符(仅一个switch语句)进行任何密集的操作。

It is probably better to use a char in this case, assuming you want to store it and process it often latter, otherwise you can just directly access the string individual char s using operator[] . 在这种情况下,最好使用char ,假设您要存储它并在以后经常处理它,否则,您可以使用operator[]直接访问单个char string One thing to note is that std::string implements the so-called short string optimization , which should be quite fast. 需要注意的一件事是std::string实现了所谓的短字符串优化 ,它应该相当快。 But anyway, you should profile your code , and unless you need a std::string (eg to be passed around latter in some other functions), you should just use a char . 但是无论如何, 您应该分析代码 ,除非需要std::string (例如,在其他一些函数中传递给后者),否则应该只使用char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM