vector methods c++ code example
Example 1: how to create a vector in c++
#include <vector>
using namespace std;
int main()
{
vector<int> vect;
vect.push_back(10);
for (int x : vect)
cout << x << " ";
return 0;
}
Example 2: c++ vector
#include <vector>
int main() {
std::vector<int> v;
v.push_back(10);
v.push_back(20);
v.pop_back();
v.push_back(30);
auto it = v.begin();
int x = *it;
++it;
int y = *it;
++it;
bool is_end = it == v.end();
return 0;
}
Example 3: vector in c++
vector<int> g1;
for (int i = 1; i <= 5; i++)
g1.push_back(i);
cout << "Output of begin and end: ";
for (auto i = g1.begin(); i != g1.end(); ++i)
cout << *i << " ";
cout << "\nOutput of cbegin and cend: ";
for (auto i = g1.cbegin(); i != g1.cend(); ++i)
cout << *i << " ";
cout << "\nOutput of rbegin and rend: ";
for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << *ir << " ";
Example 4: vector functions c++
Iterators
-----------------------------------------
begin | Returns an iterator to the beginning
end | Returns an iterator to the end
Capacity
-----------------------------------------
empty | Checks whether the container is empty
size | Returns the number of elements
reserve | Reserves storage
capacity | Returns the number of elements that can be held in currently allocated storage
Element access
-----------------------------------------
at | Access specified element with bounds checking
front | Access the first element
back | Access the last element
operator[] | Access specified element
Modifiers
-----------------------------------------
clear | Clears the contents
insert | Inserts elements
emplace | Constructs element in-place
erase | Erases elements
push_back | Adds an element to the end
emplace_back | Constructs an element in-place at the end
pop_back | Removes the last element
resize | Changes the number of elements stored
swap | Swaps the contents
*Notes*
- https:
- https:
- https: