vector::begin() เป็น Bidirectional Iterator คืนค่า Iterator ชี้ไปที่สมาชิกแรกของ Container
vector::end() เป็น Bidirectional Iterator คืนค่า Iterator ชี้ไปที่ตำแหน่งหลังสมาชิกสุดท้าย (Past-the-end)
อัลกอริทึม
Begin
Initialize vector v
Declare vector v1 and iterator it
Insert elements into vector
Print elements
End.โค้ดตัวอย่าง
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {50,60,70,80,90}, v1;
vector<int>::iterator it;
it = v.insert(v.begin(), 40); // insert at beginning
it = v.insert(v.begin(), 1, 30); // insert with count at beginning
cout << "The vector1 elements are: ";
for (it = v.begin(); it != v.end(); ++it) cout << *it << " " << endl;
v1.insert(v1.begin(), v.begin(), v.end()); // copy all using begin/end
cout << "The vector2 elements are: ";
for (it = v1.begin(); it != v1.end(); ++it) cout << *it << " " << endl;
return 0;
}ผลลัพธ์
The vector1 elements are: 30 40 50 60 70 80 90 The vector2 elements are: 30 40 50 60 70 80 90