mardi 12 juillet 2022

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

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

Aucun commentaire:

Enregistrer un commentaire