- 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
推薦閱讀
- Getting Started with ResearchKit
- 無代碼編程:用云表搭建企業數字化管理平臺
- 機器人Python青少年編程開發實例
- DevOps Automation Cookbook
- Rust Cookbook
- JavaScript:Moving to ES2015
- 飛槳PaddlePaddle深度學習實戰
- Python編程從0到1(視頻教學版)
- 軟件品質之完美管理:實戰經典
- 計算機應用基礎實踐教程
- Access 2010中文版項目教程
- Visual Basic程序設計習題與上機實踐
- 深入實踐Kotlin元編程
- ActionScript 3.0從入門到精通(視頻實戰版)
- 嵌入式Linux C語言程序設計基礎教程