C++ STL list, assign() 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++ assign() to erase elements from a list and copies a new set of elements to the target list in C++ programming

To show: How to use the C++ list, assign() to erase elements from a list and copies a new set of elements to the target list in C++ programming

 

// C++ STL list, assign()

#include <list>

#include <iostream>

using namespace std;

 

int main(void)

{

// list containers

list<int> con1, con2;

// list iterator

list<int>::const_iterator cIter;

 

// push/insert data into the list

con1.push_back(10);

con1.push_back(20);

con1.push_back(30);

con2.push_back(40);

con2.push_back(50);

con2.push_back(60);

 

// print data and do some operations

cout<<"con1 list: ";

for (cIter = con1.begin(); cIter != con1.end(); cIter++)

cout<<" "<<*cIter;

cout<<endl;

con1.assign(++con2.begin(), con2.end());

cout<<"\nOperation: con1.assign(++con2.begin(), con2.end());"<<endl;

cout<<"con1 list: ";

for (cIter = con1.begin(); cIter != con1.end(); cIter++)

cout<<" "<<*cIter;

cout<<endl;

con1.assign(9, 7);

cout<<"\nOperation: con1.assign(9, 7);"<<endl;

cout<<"con1 list: ";

for (cIter = con1.begin(); cIter != con1.end(); cIter++)

cout<<" "<<*cIter;

cout<<endl;

return 0;

}

 

Output examples:

 

con1 list: 10 20 30

Operation: con1.assign(++con2.begin(), con2.end());

con1 list: 50 60

Operation: con1.assign(9, 7);

con1 list: 7 7 7 7 7 7 7 7 7

Press any key to continue . . .

 

 

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