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

更新于: 2019 年 7 月 30 日

5K+ 浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告