简体   繁体   中英

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 ).

I strongly suspect that it's more efficient to use a char , ie

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).

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[] . One thing to note is that std::string implements the so-called short string optimization , which should be quite fast. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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