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

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
主站蜘蛛池模板: 朔州市| 宣化县| 三原县| 玛纳斯县| 沧源| 澎湖县| 吉安县| 萝北县| 吉安县| 会昌县| 伽师县| 馆陶县| 文山县| 成都市| 江西省| 四子王旗| 江源县| 咸阳市| 新晃| 嘉禾县| 浦江县| 商都县| 邻水| 神池县| 平塘县| 揭西县| 集安市| 江陵县| 瓮安县| 金湖县| 方山县| 富顺县| 惠安县| 衡南县| 长春市| 武川县| 晋江市| 长治市| 中宁县| 钟祥市| 金门县|