C++ STL vector, pop_back(), back() and push_back() code 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++ back() to return a reference to the last element of the vector, pop_back() to delete the element at the end of the vector and push_back() to add an element to the end of the vector in C++ programming

To show: How to use the C++ back() to return a reference to the last element of the vector, pop_back() to delete the element at the end of the vector and push_back() to add an element to the end of the vector in C++ programming

 

// C++ STL vector, pop_back(), back() and push_back()

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec1;

unsigned int i;

 

// push data into the vector container

vec1.push_back(4);

vec1.push_back(7);

vec1.push_back(3);

 

// print the data and do some operations

cout<<"vec1 vector data: ";

for(i=0; i<vec1.size(); ++i)

cout<<vec1[i]<<' ';

cout<<endl;

cout<<"\nOperation: vec1.back();"<<endl;

cout<<"Data: "<<vec1.back()<<endl;

cout<<"\nOperation: push_back(2);"<<endl;

vec1.push_back(2);

cout<<"Data: "<<vec1.back()<<endl;

cout<<"New vec1 vector data: ";

for(i=0; i<vec1.size(); ++i)

cout<<vec1[i]<<' ';

cout<<endl;

cout<<"\nOperation: vec1.pop_back();"<<endl;

vec1.pop_back();

cout<<"Data: "<<vec1.back()<<endl;

cout<<"New vec1 vector data: ";

for(i=0; i<vec1.size(); ++i)

cout<<vec1[i]<<' ';

cout<<endl;

return 0;

}

 

Output examples:

 

vec1 vector data: 4 7 3

Operation: vec1.back();

Data: 3

Operation: push_back(2);

Data: 2

New vec1 vector data: 4 7 3 2

Operation: vec1.pop_back();

Data: 3

New vec1 vector data: 4 7 3

Press any key to continue . . .

 

 

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