vector::end( )与vector::back( )

vector::end( )返回的是vector最后一个元素后的”结束元素“

vector::back( )返回的是vector最后一个元素

类比字符串,end( )返回的是’\0’,back( )返回的是字符串的最后一个字符

如果试图对vector::end( )返回的元素(结束元素)进行操作,将导致如下错误:

vector iterator not dereferencable

下面详细介绍两个函数并举例说明——


vector::end

Returns an iterator referring to the past-the-end element in the vector container.

The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.

Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container.

If the container is empty, this function returns the same as vector::begin.

Example

// vector::begin/end
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;
  for (int i=1; i<=5; i++) myvector.push_back(i);

  cout << "myvector contains:";
  for (vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it){
    cout << ' ' << *it;
  }
  cout << '\n';

  return 0;
}

Output

myvector contains: 1 2 3 4 5

vector::back

Returns a reference to the last element in the vector.

Unlike member vector::end, which returns an iterator just past this element, this function returns a direct reference.

Calling this function on an empty container causes undefined behavior.

Example

// vector::back
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector;

  myvector.push_back(10);

  while (myvector.back() != 0)
  {
    myvector.push_back ( myvector.back() -1 );
  }

  cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size() ; i++){
    cout << ' ' << myvector[i];
  }
  cout << '\n';

  return 0;
}

Output

myvector contains: 10 9 8 7 6 5 4 3 2 1 0
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页