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

  • Mastering C++ Programming
  • Jeganathan Swaminathan
  • 210字
  • 2021-07-02 18:28:49

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
主站蜘蛛池模板: 昌宁县| 小金县| 沙坪坝区| 东城区| 枣庄市| 清河县| 湖北省| 宝兴县| 克拉玛依市| 彝良县| 高尔夫| 兴化市| 兰溪市| 辰溪县| 蒙自县| 曲麻莱县| 灵石县| 松阳县| 鄂托克旗| 驻马店市| 德昌县| 安福县| 长宁区| 盘锦市| 长兴县| 深泽县| 巴彦淖尔市| 滨海县| 龙门县| 黄梅县| 汉川市| 商河县| 平远县| 虹口区| 福泉市| 信丰县| 营口市| 南丹县| 来安县| 长汀县| 安义县|