简体   繁体   中英

Curly bracket syntax and iterator in c++

I have question about C++11. I know the function below reverses a string, but I don't know what is {} syntax? What type of structure is that? I usually code in Java. I cannot figure it out that what is this?

string reverseString(string str){
    return{ str.rbegin(), str.rend() };
}

I also have another question, how efficient is this method to reverse a string? Because I think to reverse we should change the location of characters if we want to have string that is continuous on the memory.

This code can be also written as:

string reverseString(string str){
    return string(str.rbegin(), str.rend());
}

It uses range constructor which creates new string from two iterators (beginning and end).

Thanks to uniform initialization you can write it as:

string reverseString(string str){
    return string{str.rbegin(), str.rend()};
}

And since the compiler already knows that the return type is string , you don't have to specify it explicitly, which leads to this "weird" syntax:

string reverseString(string str){
    return {str.rbegin(), str.rend()};
}

What's being used is called Uniform Initialization .

Looks a bit odd, I admit. The function knows it needs to return a string , but it's been fed a pair of iterators. The curly braces allow the compiler to attempt to construct a string based on the contents of the braces, and sure enough, constructor number six listed here will attempt to construct a string from a begin and end iterator.

So

return {str.rbegin(), str.rend()};

is in more familiar syntax

return string(str.rbegin(), str.rend());

The next bit of magic is rbegin and rend provide reverse iterators, so the input string will be read backward into the output string .

string iterators are Random Access Iterators , so the iterator will be traversed in O(N) time. There isn't that much magic in building the new string, copying the old string and maybe some buffer resizing, the new string will be built in O(N) time PLUS any time required to size the buffer backing the new string .

This results in either

  • O(N) complexity because the buffer is presized before copying copying N elements from one string to the other, or
  • Amortized O(N) complexity because the buffer is resized on demand, resulting in some additional allocating and copying of old buffer to new as well as copying from one string to the other.

The second option is possible because the string constructor does not require the input iterator to be random access, making computing the size of the required buffer for presizing potentially more expensive than resizing. But it might have a special case testing for random access and presizing.

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