C ++ STL中的vector :: begin()和vector :: end()
vector::begin()函数是一个双向迭代器,用于返回指向容器第一个元素的迭代器。
vector::end()函数是一个双向迭代器,用于返回指向容器最后一个元素的迭代器。
算法
Begin Initialize the vector v. Declare the vector v1 and iterator it to the vector. Insert the elements of the vector. Print the elements. End.
范例程式码
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = { 50,60,70,80,90}, v1; //declaring v(with values), v1 as vector.
vector<int>::iterator it;
//declaring an ierator
it = v.insert(v.begin(), 40);
//inserting a value in v vector with specified the position at the beginning using the function begin().
it = v.insert(v.begin(), 1, 30);
//inserting a value with its size in v vector with specified the position at the beginning using the function begin().
cout << "The vector1 elements are: ";
for ( it = v.begin(); it != v.end(); ++it)
cout << *it << " "<<endl; // printing the values of v vector
v1.insert(v1.begin(),v.begin(),v.end());
//inserting all values from beginning to end, by using begin() and end() function, of v
vector in v1 vector pointing at the beginning using begin() function.
cout << "The vector2 elements are: ";
for (it = v1.begin(); it != v1.end(); ++it)
cout << *it << " "<<endl; // printing the values of v1 vector
return 0;
}输出
The vector1 elements are: 30 40 50 60 70 80 90 The vector2 elements are: 30 40 50 60 70 80 90