1

I have the following code:

string str1 = "first string";
string str2(str1, 6, 6)

// Output: string
  • 1st param points to the variable which has to be sliced
  • 2nd param tell the starting index (starting from 1)
  • 3rd param tells how many characters you want to take from str1 - basically the ending index

I understand all of the above. However, when I came across the below code block I got very confused.

Why does this work? It doesn't have 3 params.

string str3(str1.begin(), str1.begin() + 5); // Why no 3rd param ? 
// Output: first

Also here, the 2nd param goes till the 5 index as opposed to starting from there (like in the first example). Can someone explain what's different b/w code blocks 1 and 2?

Thank you.

3
  • 6
    Both are different ctors. std::string has multiple overloads Commented Jan 22, 2022 at 10:24
  • 2
    what does 'ctors' mean? Commented Jan 22, 2022 at 10:25
  • 5
    ctor is short hand for constructor. Commented Jan 22, 2022 at 10:26

1 Answer 1

3

As @Ch3steR mentioned in the comment, they are all ctors(constructors), and that particular constructor takes two parameters.

  1. Parameter is an "iterator" that points to starting character
  2. Parameter is an "iterator" that points to end character.

Here is the link on bccnsoft docs:

a string of characters denoted by the start and end iterators

Here is the link on cppreference docs:

Constructs the string with the contents of the range (first, last)

Here is the link on cplusplus docs:

(7) range constructor

Sign up to request clarification or add additional context in comments.

1 Comment

@OlafDietsche my bad! I was reading and typing on mobile phone and saw it wrong, second parameter is iterator to. I will fix it in a moment. About bccnsoft.com, of course that cppreference.com is most reliable for c++ docs, but I estimated that cppreference.com would just confuse him, as his knowledge is very basic. And I believe there is nothing wrong about bccnsoft.com, I did reference on it a lot of the time with success.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.