C++ STL basic_string::begin() iterator program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the C++ basic_string::begin() iterator which return an iterator addressing the first element in the string in C++ programming
To show: How to use the basic_string begin() iterator which return an iterator addressing the first element in the string in C++ programming
// C++ STL basic_string, iterator, begin()
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
// container and iterators
string str1 ("This is a test string."), str2;
basic_string <char>::iterator strp_Iter, str1_Iter, str2_Iter;
basic_string <char>::const_iterator str1_cIter;
str1_Iter = str1.begin();
// printing the data
cout<<"\nOperation: str1_Iter = str1.begin()"<<endl;
cout<<"The first character of the string str1 is: "<<*str1_Iter<<endl;
cout<<"The full original string str1 is: "<<str1<<endl;
// the dereferenced iterator can be used to modify a character
*str1_Iter = 'G';
cout<<"\nOperation: *str1_Iter = \'G\'"<<endl;
cout<<"The first character of the modified string str1 is now: "<<*str1_Iter<<endl;
cout<<"The full modified string str1 is now: "<<str1<<endl;
// the following line would be an error because iterator is const
//
// *str1_cIter = 'g';
//
// for an empty string, begin() is equivalent to end()
cout<<"\nOperation: *str2.begin() == str2.end()?"<<endl;
if (str2.begin() == str2.end())
cout<<"The string str2 is empty."<<endl;
else
cout<<"The string str2 is not empty."<<endl;
return 0;
}
Output examples:
Operation: str1_Iter = str1.begin()
The first character of the string str1 is: T
The full original string str1 is: This is a test string.
Operation: *str1_Iter = 'G'
The first character of the modified string str1 is now: G
The full modified string str1 is now: Ghis is a test string.
Operation: *str2.begin() == str2.end()?
The string str2 is empty.
Press any key to continue . . .