C++ STL vector, assign() 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++ assign() to erase a vector and copies the specified elements to the empty vector in C++ programming

To show: How to use the C++ assign() to erase a vector and copies the specified elements to the empty vector in C++ programming

 

// C++ STL vector, assign()

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec2;

// vector iterator

vector <int>::iterator Iter;

unsigned int x = 2, y = 8;

 

// push data into vector container

vec2.push_back(1);

vec2.push_back(5);

vec2.push_back(3);

vec2.push_back(4);

vec2.push_back(5);

vec2.push_back(3);

vec2.push_back(7);

vec2.push_back(8);

vec2.push_back(4);

 

// print the data and do some operations

cout<<"Operation: vec2.begin() and vec2.end();"<<endl;

cout<<"vec2 vector data: ";

for(Iter = vec2.begin(); Iter != vec2.end(); Iter++)

cout<<*Iter<<" ";

cout<<endl<<endl;

cout<<"Operation: vec2.assign(5, 7);"<<endl;

vec2.assign(5, 7);

cout<<"vec2 vector data: ";

for(Iter = vec2.begin(); Iter != vec2.end(); Iter++)

cout<<*Iter<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

Operation: vec2.begin() and vec2.end();

vec2 vector data: 1 5 3 4 5 3 7 8 4

Operation: vec2.assign(5, 7);

vec2 vector data: 7 7 7 7 7

Press any key to continue . . .

 

 

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