Another C++ begin() and end() member function program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

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++ begin() to return an iterator addressing the first element in the string and end() to return an iterator that addresses the location succeeding the last element in a string in C++ programming

To show: How to use the C++ begin() and end() member function to return an iterator addressing the first element in the string and to return an iterator that addresses the location succeeding the last element in a string in C++ programming

 

// the C++ begin() and end() member function code sample

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

string str1("Testing the end()");

basic_string <char>::iterator StrIter, Str1Iter;

Str1Iter = str1.end();

 

// minus the null character, so point to the real last character in the string

Str1Iter--;

cout<<"Operation: str1.end() then Str1Iter--"<<endl;

cout<<"str1 string is: "<<str1<<endl;

cout<<"The last character of the str1 string is: "<<*Str1Iter<<endl;

 

// end() used to test when an iterator has reached the end of its string

cout<<"Using forward iterator the str1 is: ";

for(StrIter = str1.begin(); StrIter != str1.end(); StrIter++)

cout<<*StrIter;

cout<<"\n\n";

 

// the dereferenced iterator can be used to modify a character

// the last event, this pointer point to the last character in the string

*Str1Iter = 'F';

cout<<"Operation: *Str1Iter = 'F'"<<endl;

cout<<"Now, the last character of the modified str1 is: "<<*Str1Iter<<endl;

cout<<"Then the modified str1 string is: "<<str1<<endl;

 

return 0;

}

 

Output example:

 

Operation: str1.end() then Str1Iter--

str1 string is: Testing the end()

The last character of the str1 string is: )

Using forward iterator the str1 is: Testing the end()

 

Operation: *Str1Iter = 'F'

Now, the last character of the modified str1 is: F

Then the modified str1 string is: Testing the end(F

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index