Stl doubts why c_str method used and pair type array

  1. why c_str is used after searching i got to know c_str is used to convert a string to cstring which can be used in old c functions and so why in particular (char *)str.c_str() is used??(i remeber in video sir mentioned its underlining array but i am unable to understand it beside same thing was not done in previous lectures while using strok though there datatype was not string)

2)why pair is used to store key and string in generall ,can we use vectors or map ? was there any advantage of pair over them?

@himanshu0ayush hey c_str returns a const char* that points to a null-terminated string (i.e. a C-style string). It is useful when you want to pass the "contents"¹ of an std::string to a function that expects to work with a C-style string.

For example, consider this code:

std::string str(“Hello world!”);
int pos1 = str.find_first_of(‘w’);

int pos2 = strchr(str.c_str(), ‘w’) - str.c_str();

if (pos1 == pos2) {
printf(“Both ways give the same result.\n”);
}
See it in action.

Notes:

¹ This is not entirely true because an std::string (unlike a C string) can contain the \0 character. If it does, the code that receives the return value of c_str() will be fooled into thinking that the string is shorter than it really is, since it will interpret \0 as the end of the string.
2. Pair hmne just hmne ek double cheezon ki pairing ke lie hn ap map vector bhi use kr skte ho ,nothing much difference.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.