官术网_书友最值得收藏!

Vector 

Vector is a quite useful sequence container, and it works exactly as an array, except that the vector can grow and shrink at runtime while an array is of a fixed size. However, the data structure used under the hood in an array and vector is a plain simple built-in C/C++ style array.  

Let's look at the following example to understand vectors better:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main () {
vector<int> v = { 1, 5, 2, 4, 3 };

cout << "\nSize of vector is " << v.size() << endl;

auto pos = v.begin();

cout << "\nPrint vector elements before sorting" << endl;
while ( pos != v.end() )
cout << *pos++ << "\t";
cout << endl;

sort( v.begin(), v.end() );

pos = v.begin();

cout << "\nPrint vector elements after sorting" << endl;

while ( pos != v.end() )
cout << *pos++ << "\t";
cout << endl;

return 0;
}

The preceding code can be compiled and the output can be viewed with the following commands:

g++ main.cpp -std=c++17
./a.out

The output of the program is as follows:

Size of vector is 5

Print vector elements before sorting
1 5 2 4 3

Print vector elements after sorting
1 2 3 4 5
主站蜘蛛池模板: 酒泉市| 荆门市| 正定县| 开阳县| 密云县| 陇川县| 许昌市| 弥勒县| 张家川| 伊吾县| 栖霞市| 嘉义市| 石景山区| 布尔津县| 淄博市| 江都市| 延安市| 夹江县| 西昌市| 额济纳旗| 西丰县| 修水县| 扶绥县| 铅山县| 平山县| 靖州| 义马市| 三亚市| 南开区| 梁山县| 板桥市| 西乡县| 比如县| 日土县| 马山县| 敖汉旗| 饶河县| 台东县| 涡阳县| 巴马| 偃师市|