- 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
推薦閱讀
- Python概率統計
- R語言數據分析從入門到精通
- Java 開發從入門到精通(第2版)
- Learning Real-time Processing with Spark Streaming
- GraphQL學習指南
- Spring Cloud Alibaba微服務架構設計與開發實戰
- Learn to Create WordPress Themes by Building 5 Projects
- 微服務設計原理與架構
- Access 2010數據庫基礎與應用項目式教程(第3版)
- Android 應用案例開發大全(第3版)
- Getting Started with React Native
- RocketMQ實戰與原理解析
- Oracle Data Guard 11gR2 Administration Beginner's Guide
- 用Go語言自制編譯器
- Illustrator CS6中文版應用教程(第二版)