Reputation: 83
I am trying to create a string by accessing its individual index positions and trying to print it.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s="";
s[0]='a';
s[1]='b';
s[2]='c';
s[3]='d';
cout << s << endl;
for(int i = 0; i < 4; i++)
cout << s[i] << endl;
return 0;
}
This doesn't print a entire string but does print its individual characters.
Following code prints both the strings and its individual characters.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s=" ";
s[0]='a';
s[1]='b';
s[2]='c';
s[3]='d';
cout << s << endl;
for(int i = 0; i < 4; i++)
cout << s[i] << endl;
return 0;
}
Why does this happen. Links to any further reading are appreciated.
Upvotes: 0
Views: 165
Reputation: 57
String, similarly to some other STL(Standard template library) classes is a dynamic template class. What you're doing in your code is creating an empty string and then trying to insert elements into non-existing indices, which in an STL type class means you try to access a memory which was not allocated.
What you want to do when inserting elements into your string is use the push_back
method, which will insert elements to the end of your string (and handle the memory allocation automatically).
If you know how many elements will be inserted before performing those actions, you can minimize the number of memory allocations by using the reserve
method before using push_back
.
For example, in your code we could opt to something like this:
s.reserve(5);
s.push_back('a');
s.push_back('b');
s.push_back('c');
s.push_back('d');
If we do not reserve memory ahead there could be more allocations and de-allocations as the string increases in size which can be expensive.
Upvotes: 0
Reputation: 87962
Strings don't grow automatically
This string has zero size
string s="";
This code is an error because s[0]
does not exist (since the string has zero size).
s[0]='a';
Because this is an error your program has undefined behaviour, which means any output is possible, including the strange behaviour you see.
If you want to add a character to a string use push_back
(or +=
)
s.push_back('a');
s.push_back('b');
s.push_back('c');
s.push_back('d');
Now that the string has some characters you can use []
to access them (or change them).
Upvotes: 2