0

Is there a time difference in accessing each char using the [] operator vs calling string's iterator? I'm very curious about the time complexity of using the [] operator, since I couldn't find it online

http://www.cplusplus.com/reference/string/string/operator[]/

I also heard that it's better to use a range based loop like

void print(const std::string &s)
{
    for (char const &c: s) {
        std::cout << c << ' ';
    }
}

Would this perform better than using an iterator?

Shisui
  • 1,051
  • 1
  • 8
  • 23
  • 1
    Does this answer your question? [For every character in string](https://stackoverflow.com/questions/9438209/for-every-character-in-string) – Jan Schultke Aug 19 '20 at 22:15
  • Use a range-based for-loop. Range based for loops use iterators. They're just syntax sugar. It won't make any difference. – Jan Schultke Aug 19 '20 at 22:16
  • 1
    I would expect them to be equally efficient after optimization (compilers are smart these days) however the range based for loop is easier to use and certainly easier to read. – drescherjm Aug 19 '20 at 22:17
  • ***Is there a time difference in accessing each char using the [] operator vs calling string's iterator?*** Make a string of a few MB in length and see. Make sure you test a Release / optimized build. – drescherjm Aug 19 '20 at 22:20
  • 3
    Side note: You almost never need the most efficient. Pick the simplest, profile the code to see if it is fast enough. If it isn't, try something a little more complicated. Profile it to see that it really is faster and proceed to an even more difficult method if it's still not efficient enough. – user4581301 Aug 19 '20 at 22:21
  • There is no efficient method. Look at the assembly language. All you are doing is changing the syntax of the loop. You still have to perform the basics: 1) Access the string location; 2) process the character; 3) increment the loop variable; 4) check loop variable against limit. – Thomas Matthews Aug 20 '20 at 02:19

0 Answers0