Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between subscript [] operator and push_back method for inserting charachter in a string in C++

I am stuck on this stupid doubt and can’t understand which part have I understood wrong.
I am trying to fill an empty string and I thought of doing it using the subscipt [] operator but found that although loop runs perfectly but the final string is still empty with size zero. However push_back runs perfectly fine. I can use push_back but want to understand the reason for the first one. If anyone can clarify?

string r;
int i;
for(i = 0; i < 5; ++i)
{
     r[i] = 'a';
}
cout << r.size();    //output: 0
cout << endl;

for(i = 0; i < 5; ++i)
{
    r.push_back('a');
}
cout << r.size();    //output: 5

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As simple as it is for std::vector, std::string doesn’t have bounds check when using subscript operator. When creating empty string, you have a collection of zero length, thus when you assign values by index, the values are assigned to memory out of the collection’s bounds

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading