-
string iterator
I'm reading one tutorial about STL iterators. I've noticed that there is iterator support for strings. For example I can do something lke this:
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s("Kivla");
string::iterator it;
for (it = s.begin(); it != s.end();++it)
{
cout<<*it;
}
}
I wonder what is the benefit of using iterators with strings (there must be some benefit otherwise iterators wouldn't have been defined)?
In which cases they are useful for strings?
- Micko
-
They are usefull in all the situations where you want to use the string object with the STL.
Code:
#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string s("Kivla");
cout << "Before toupper: " << s << endl;
transform(s.begin(),s.end(),s.begin(),toupper);
cout << "After toupper : " << s << endl;
sort(s.begin(),s.end());
cout << "After sort : " << s << endl;
return 0;
}
Output:
Code:
Before toupper: Kivla
After toupper : KIVLA
After sort : AIKLV
-
This is a contrived multi-example, but it's not a big step to a potential real world use:
Code:
#include <deque>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s ( "is a test" );
string t ( "This " );
deque<char> string_buffer ( s.begin(), s.end() );
for ( string::reverse_iterator it = t.rbegin(); it != t.rend(); ++it )
string_buffer.push_front ( *it );
s = string ( string_buffer.begin(), string_buffer.end() );
cout<< s <<endl;
}
-
Hmm, interesting, I'll dive more into STL... I almost sure I'll have questions regarding STL very soon. I hope I can count on your help.
Thanks hk_mp5kpdw and thanks Prelude
-
well if you think of strings as just another container then:
1: You have consistency with the other container
2: Many(most) of the std::algorithm functions use iterators as others have shown by example
-
Well, I'm pretty new to STL, I was playing with string class and container vector from time to time, but never actually scratch under the surface. Of coures that is going to change very soon...