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

  • 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
主站蜘蛛池模板: 谢通门县| 辽阳县| 香河县| 丹江口市| 宣城市| 金湖县| 龙游县| 连云港市| 安仁县| 七台河市| 临潭县| 邵阳市| 青州市| 武平县| 磐安县| 新干县| 高清| 井研县| 嘉鱼县| 西盟| 银川市| 汉寿县| 沁阳市| 太谷县| 韶山市| 龙海市| 西昌市| 布尔津县| 张家界市| 桐梓县| 两当县| 定结县| 郁南县| 酒泉市| 秭归县| 永善县| 精河县| 孟州市| 华阴市| 五华县| 廊坊市|