Vector
#include <vector> // include vector in code
vector<int> arr; // create an empty vector
vector<int> arr(10); // create a vector of size 10
vector<int> arr{1,2,3}; // create vector with values 1,2,3
vector<int> arr(10, 5); // create an arr of size 10, all elements initialised to 5
int n = arr.size(); // get number of elements in arr
// check if vector is empty
if (arr.empty()){
cout << "arr is empty";
}
arr.push_back(3); // add element at end of vector
arr.insert(arr.begin(), 7); // add an element at beginning of vector
arr.insert(arr.end(), brr.begin(), brr.end()); // add another vector at end of a vector
arr.clear(); // clear all enteries
// sort vector elements
sort(arr.begin(), arr.end());
// sort vector elements in descending order using a comparator function
sort(arr.begin(), arr.end(), [](int lhs, int rhs){
return (lhs > rhs); // read it like: lhs should come before rhs if (lhs > rhs)
});
Last updated