define vector 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: how to initialize vector in c++ with all elements 0
vector<int> arr(10,0);
Example 4: vector c++
Vectors are sequence container that can change size. Container is a objects
that hold data of same type. Sequence containers store elements strictly in
linear sequence.
Vector stores elements in contiguous memory locations and enables direct access
to any element using subscript operator []. Unlike array, vector can shrink or
expand as needed at run time. The storage of the vector is handled automatically.
To support shrink and expand functionality at runtime, vector container may
allocate some extra storage to accommodate for possible growth thus container
have actual capacity greater than the size. Therefore, compared to array, vector
consumes more memory in exchange for the ability to manage storage and grow
dynamically in an efficient way.
Zero sized vectors are also valid. In that case vector.begin() and vector.end()
points to same location. But behavior of calling front() or back() is undefined.
Example 5: declare vectors c++
vector<int> vec;
vector<int> vec(4);
vector<int> vec(4, 42);
vector<int> vec(4, 42);
vector<int> vec2(vec);
Example 6: 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 << " ";