vector::front 和 vector::back
在 Visual C++ 演示如何使用 向量:: 前面 和 向量:: 返回 标准 (STL)模板库函数。
template<class _TYPE, class _A>
reference vector::front( );
template<class _TYPE, class _A>
reference vector::back( );
备注
备注
类/参数名在原型不匹配版本在头文件。修改某些提高可读性。
此示例声明整数一个空的向量与成员 [100, 200, 300, 400] 的。 其中显示了个矢量的第一个元素使用 vector::front 获取它。 其中显示了个矢量的最后一个元素使用 vector::back 获取它。 使用 vector::size,其中显示了个矢量的元素的数目。 使用 vector::back,该示例将清除个矢量使用 vector::end – 1 的最后一个元素,然后显示新的最后一个元素。 使用 vector::begin,使用 vector::front,它将清除个矢量的第一个元素,然后显示新的第一个元素。 最后,该示例显示保持在这个矢量的元素数使用 vector::size。
示例
// frontback.cpp
// compile with: /EHsc
//
// Illustrates the vector::front and vector::back methods.
//
// Functions:
//
// vector::front - Returns reference to first element of vector.
//
// vector::back - Returns reference to last element of vector.
//
// vector::push_back - Appends (inserts) an element to the end of a
// vector, allocating memory for it if necessary.
//
// vector::size - Returns number of elements in the vector.
//
// vector::begin - Returns an iterator to start traversal of the vector.
//
// vector::end - Returns an iterator for the last element of the vector.
//
// vector::erase - Deletes elements from a vector (single & range).
//
//////////////////////////////////////////////////////////////////////
// The debugger can't handle symbols more than 255 characters long.
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is issued.
#pragma warning(disable:4786)
#include <iostream>
#include <vector>
using namespace std ;
typedef vector<int> INTVECTOR;
const int ARRAY_SIZE = 4;
int main()
{
// Dynamically allocated vector begins with 0 elements.
INTVECTOR theVector;
// Intialize the array to contain the members [100, 200, 300, 400]
for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
theVector.push_back((cEachItem + 1) * 100);
cout << "First element: " << theVector.front() << endl;
cout << "Last element: " << theVector.back() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
// Delete the last element of the vector. Remember that the vector
// is 0-based, so theVector.end() actually points 1 element beyond
// the end.
theVector.erase(theVector.end() - 1);
cout << endl << "After erasing last element, new last element is: "
<< theVector.back() << endl;
// Delete the first element of the vector.
theVector.erase(theVector.begin());
cout << "After erasing first element, new first element is: "
<< theVector.front() << endl;
cout << "Elements in vector: " << theVector.size() << endl;
}
Output
First element: 100
Last element: 400
Elements in vector: 4
After erasing last element, new last element is: 300
After erasing first element, new first element is: 200
Elements in vector: 2
要求
标题: vector