Vector in C++ STL

Vector in C++ STL

Vector Container:

ยท

14 min read

DESCRIPTION:

  • Dynamic array with efficient random access and insertion at the end.

  • Resembles a list that automatically grows as elements are added.

  • Ideal for storing ordered collections with frequent access by index.

  • Supports automatic resizing of storage for insertion and deletion.


ALL THE POSSIBLE WAY TO DECLARE, INITIALIZE AND PRINTING VECTOR:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {

// Declaration of an empty vector of integers

vector<int> myVector;

// Declaration of a vector of doubles

vector<double> doubleVector;

// Declaration of a vector of strings

vector<string> stringVector;

// Initializing vector with values using initializer list

vector<int> initializedVector = {1, 2, 3, 4, 5};

// Initializing vector with a specific size and default value

vector<int> sizedVector(5, 0); // Vector of size 5, all elements initialized to 0

// Dynamic initialization using push_back

vector<int> dynamicVector;

dynamicVector.push_back(10);

dynamicVector.push_back(20);

dynamicVector.push_back(30);

// Copying from another vector

vector<int> sourceVector = {1, 2, 3, 4, 5};

vector<int> copiedVector(sourceVector); // Copy constructor

// Printing vector using for loop with index

cout << "Initialized Vector (index): ";

for (int i = 0; i < initializedVector.size(); ++i) {

cout << initializedVector[i] << " ";

}

cout << endl;

// Printing vector using for loop and vector.begin()

cout << "Sized Vector (vector.begin()): ";

for (auto it = sizedVector.begin(); it != sizedVector.end(); ++it) {

cout << *it << " ";

}

cout << endl;

// Printing vector using for loop and iterator

cout << "Dynamic Vector (iterator): ";

for (vector<int>::iterator it = dynamicVector.begin(); it != dynamicVector.end(); ++it) {

cout << *it << " ";

}

cout << endl;

// Printing vector using for loop and auto keyword

cout << "Copied Vector (auto): ";

for (auto element : copiedVector) {

cout << element << " ";

}

cout << endl;

return 0;

}

OUTPUT:

Initialized Vector (index): 1 2 3 4 5
Sized Vector (vector.begin()): 0 0 0 0 0
Dynamic Vector (iterator): 10 20 30
Copied Vector (auto): 1 2 3 4 5

MEMBER FUNCTIONS:

  1. At(g):

    • Works: Returns a reference to the element at position 'g' in the vector.

    • Syntax: myVector.at(g)

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        int elementAtPositionG = myVector.at(2);
      
  2. Front:

    • Works: Returns a reference to the first element in the vector.

    • Syntax: myVector.front()

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        int firstElement = myVector.front();
      
  3. Back:

    • Works: Returns a reference to the last element in the vector.

    • Syntax: myVector.back()

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        int lastElement = myVector.back();
      
  4. Data:

    • Works: Returns a direct pointer to the memory array used internally in the vector.

    • Syntax: myVector.data()

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        int* dataPointer = myVector.data();
      
  5. Size:

    • Works: Returns the number of elements in the vector.

    • Syntax: myVector.size()

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        std::size_t vectorSize = myVector.size();
      
  6. Max Size:

    • Works: Returns the maximum number of elements that the vector can hold.

    • Syntax: myVector.max_size()

    • Example:

        vector<int> myVector;
        std::size_t maxVectorSize = myVector.max_size();
      
  7. Capacity:

    • Works: Returns the size of the allocated storage space.

    • Syntax: myVector.capacity()

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        std::size_t vectorCapacity = myVector.capacity();
      
  8. Resize(n):

    • Works: Resizes the vector to contain 'n' elements.

    • Syntax: myVector.resize(n)

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        myVector.resize(7);
      
  9. Empty:

    • Works: Returns whether the vector is empty.

    • Syntax: myVector.empty()

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        bool isEmpty = myVector.empty();
      
  10. Shrink to Fit:

    • Works: Reduces capacity to fit size and destroys excess elements.

    • Syntax: myVector.shrink_to_fit()

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        myVector.shrink_to_fit();
      
  11. Reserve(n):

    • Works: Requests capacity to be at least 'n' elements.

    • Syntax: myVector.reserve(n)

    • Example:

        vector<int> myVector;
        myVector.reserve(10);
      
  12. Begin(), End(), Rbegin(), Rend():

    • Works: Iterator functions for the vector.

    • Syntax: myVector.begin(), myVector.end(), myVector.rbegin(), myVector.rend()

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        auto beginIterator = myVector.begin();
        auto endIterator = myVector.end();
        auto rbeginIterator = myVector.rbegin();
        auto rendIterator = myVector.rend();
      

Code ๐Ÿ‘

#include <iostream>
#include <vector>

using namespace std;

int main() {

// Declare a vector of integers

vector<int> myVector;

// Use push_back to add elements to the vector

myVector.push_back(10);

myVector.push_back(20);

myVector.push_back(30);

myVector.push_back(40);

// Accessing elements using at(g)

cout << "Element at position 2: " << myVector.at(2) << endl;

// Accessing the first and last elements using front() and back()

cout << "First element: " << myVector.front() << endl;

cout << "Last element: " << myVector.back() << endl;

// Using data() to get a direct pointer to the memory array

int* pointerToData = myVector.data();

cout << "Pointer to data: " << *pointerToData << endl;

// Using size(), max_size(), and capacity()

cout << "Size of the vector: " << myVector.size() << endl;

cout << "Maximum size of the vector: " << myVector.max_size() << endl;

cout << "Capacity of the vector: " << myVector.capacity() << endl;

// Using resize() to change the number of elements

myVector.resize(3);

cout << "After resizing to 3 elements, size: " << myVector.size() << endl;

// Using empty() to check if the vector is empty

cout << "Is the vector empty? " << (myVector.empty() ? "Yes" : "No") << endl;

// Using shrink_to_fit() to reduce capacity

myVector.shrink_to_fit();

cout << "After shrinking to fit, capacity: " << myVector.capacity() << endl;

// Using reserve() to request a specific capacity

myVector.reserve(10);

cout << "After reserving capacity for 10 elements, capacity: " << myVector.capacity() << endl;

// Using iterators (begin(), end(), rbegin(), rend())

cout << "Elements using iterators:";

for (auto it = myVector.begin(); it != myVector.end(); ++it) {

cout << " " << *it;

}

cout << endl;

cout << "Reverse elements using reverse iterators:";

for (auto rit = myVector.rbegin(); rit != myVector.rend(); ++rit) {

cout << " " << *rit;

}

cout << endl;

return 0;

}

OUTPUT:

Element at position 2: 30
First element: 10
Last element: 40
Pointer to data: 10
Size of the vector: 4
Maximum size of the vector: 1073741823
Capacity of the vector: 4
After resizing to 3 elements, size: 3
Is the vector empty? No
After shrinking to fit, capacity: 3
After reserving capacity for 10 elements, capacity: 10
Elements using iterators: 10 20 30
Reverse elements using reverse iterators: 30 20 10

MODIFIERS:

  1. Assign():

    • Works: Assigns new values to vector elements.

    • Syntax: myVector.assign(first_iterator, last_iterator)

    • Example:

        vector<int> myVector;
        vector<int> newValues = {1, 2, 3};
        myVector.assign(newValues.begin(), newValues.end());
      
  2. Push Back:

    • Works: Adds elements to the end of the vector.

    • Syntax: myVector.push_back(value)

    • Example:

        vector<int> myVector;
        myVector.push_back(6);
      
  3. Pop Back:

    • Works: Removes elements from the end of the vector.

    • Syntax: myVector.pop_back()

    • Example:

        vector<int> myVector;
        myVector.push_back(6);
        myVector.pop_back();
      
  4. Insert:

    • Works: Inserts new elements at a specified position.

    • Syntax: myVector.insert(iterator_position, value)

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        myVector.insert(myVector.begin() + 2, 8);
      
  5. Erase:

    • Works: Removes elements from a specified position or range.

    • Syntax: myVector.erase(position)

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        myVector.erase(myVector.begin() + 3);
      
  6. Swap:

    • Works: Swaps contents with another vector.

    • Syntax: myVector.swap(otherVector)

    • Example:

        vector<int> myVector1 = {1, 2, 3};
        vector<int> myVector2 = {4, 5, 6};
        myVector1.swap(myVector2);
      
  7. Clear:

    • Works: Removes all elements from the vector.

    • Syntax: myVector.clear()

    • Example:

        vector<int> myVector = {1, 2, 3};
        myVector.clear();
      
  8. Emplace:

    • Works: Inserts a new element at a position.

    • Syntax: myVector.emplace(iterator_position, args)

    • Example:

        vector<int> myVector = {3, 7, 2, 8, 5};
        myVector.emplace(myVector.begin() + 2, 10);
      
  9. Emplace Back:

    • Works: Inserts a new element at the end.

    • Syntax: myVector.emplace_back(args)

    • Example:

        vector<int> myVector;
        myVector.emplace_back(12);
      

CODE:

#include <iostream>
#include <vector>

using namespace std;

int main() {

// Declare a vector of integers

vector<int> myVector;

// Use assign() to assign new values to vector elements

myVector.assign({1, 2, 3, 4, 5});

cout << "After assign(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Use push_back() to add elements to the end

myVector.push_back(6);

cout << "After push_back(6): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Use pop_back() to remove the last element

myVector.pop_back();

cout << "After pop_back(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Use insert() to insert new elements at a specified position

myVector.insert(myVector.begin() + 2, 10);

cout << "After insert(myVector.begin() + 2, 10): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Use erase() to remove elements from a specified position or range

myVector.erase(myVector.begin() + 1);

cout << "After erase(myVector.begin() + 1): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Use swap() to swap contents with another vector

vector<int> anotherVector = {7, 8, 9};

myVector.swap(anotherVector);

cout << "After swap(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Use clear() to remove all elements

myVector.clear();

cout << "After clear(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Use emplace() to insert a new element at a position

myVector.emplace(myVector.begin(), 100);

cout << "After emplace(myVector.begin(), 100): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Use emplace_back() to insert a new element at the end

myVector.emplace_back(200);

cout << "After emplace_back(200): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

return 0;

}

OUTPUT:

After assign(): 1 2 3 4 5
After push_back(6): 1 2 3 4 5 6
After pop_back(): 1 2 3 4 5
After insert(myVector.begin() + 2, 10): 1 2 10 3 4 5
After erase(myVector.begin() + 1): 1 10 3 4 5
After swap(): 7 8 9
After clear():
After emplace(myVector.begin(), 100): 100
After emplace_back(200): 100 200

ALGORITHM:

  1. Binary Search:

    • Works: Conducts a binary search on an ordered sequence.

    • Syntax: std::binary_search(first_iterator, last_iterator, value)

    • Example:

        vector<int> myVector = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        bool isPresent = std::binary_search(myVector.begin(), myVector.end(), 7);
      
  2. Equal Range:

    • Works: Finds a subrange of elements with a given value.

    • Syntax: std::equal_range(first_iterator, last_iterator, value)

    • Example:

        vector<int> myVector = {1, 2, 3, 4, 5, 5, 6, 7, 8, 9};
        auto range = std::equal_range(myVector.begin(), myVector.end(), 5);
      
  3. Inplace Merge:

    • Works: Merges two consecutive sorted sequences.

    • Syntax: std::inplace_merge(first_iterator, middle_iterator, last_iterator)

    • Example:

        vector<int> myVector = {3, 5, 7, 1, 2, 4, 6, 8};
        std::inplace_merge(myVector.begin(), myVector.begin() + 3, myVector.end());
      
  4. Lower Bound:

    • Works: Finds the first occurrence of or the position to insert a specified value.

    • Syntax: std::lower_bound(first_iterator, last_iterator, value)

    • Example:

        vector<int> myVector = {1, 2, 2, 3, 4, 5};
        auto position = std::lower_bound(myVector.begin(), myVector.end(), 3);
      
  5. Make Heap:

    • Works: Creates a max heap from a sequence.

    • Syntax: std::make_heap(first_iterator, last_iterator)

    • Example:

        vector<int> myVector = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
        std::make_heap(myVector.begin(), myVector.end());
      
  6. Merge:

    • Works: Merges two sorted sequences.

    • Syntax: std::merge(first1_iterator, last1_iterator, first2_iterator, last2_iterator, output_iterator)

    • Example:

        vector<int> vec1 = {1, 3, 5};
        vector<int> vec2 = {2, 4, 6};
        vector<int> mergedVector;
        std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), std::back_inserter(mergedVector));
      
  7. Partition:

    • Works: Places elements matching a predicate in the first part.

    • Syntax: std::partition(first_iterator, last_iterator, predicate)

    • Example:

        vector<int> myVector = {1, 2, 3, 4, 5, 6};
        std::partition(myVector.begin(), myVector.end(), [](int x){ return x % 2 == 0; });
      
  8. Sort:

    • Works: Sorts a sequence.

    • Syntax: std::sort(first_iterator, last_iterator)

    • Example:

        vector<int> myVector = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
        std::sort(myVector.begin(), myVector.end());
      
  9. Sort Heap:

    • Works: Converts a max heap into a sorted range.

    • Syntax: std::sort_heap(first_iterator, last_iterator)

    • Example:

        vector<int> myVector = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
        std::make_heap(myVector.begin(), myVector.end());
        std::sort_heap(myVector.begin(), myVector.end());
      
  10. Upper Bound:

    • Works: Finds the position after the last occurrence of a specified value.

    • Syntax: std::upper_bound(first_iterator, last_iterator, value)

    • Example:

        vector<int> myVector = {1, 2, 2, 3, 4, 5};
        auto position = std::upper_bound(myVector.begin(), myVector.end(), 2);
      
  11. Stable Sort:

    • Works: Sorts while maintaining the relative order of equal elements.

    • Syntax: std::stable_sort(first_iterator, last_iterator)

    • Example:

        vector<int> myVector = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
        std::stable_sort(myVector.begin(), myVector.end());
      
  12. Max:

    • Works: Returns the greater of two values.

    • Syntax: std::max(a, b)

    • Example:

        int largerValue = std::max(5, 8);
      
  13. Max Element:

    • Works: Finds the largest element in a range.

    • Syntax: std::max_element(first_iterator, last_iterator)

    • Example:

        vector<int> myVector = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
        auto maxElement = std::max_element(myVector.begin(), myVector.end());
      
  14. Min:

    • Works: Returns the smaller of two values.

    • Syntax: std::min(a, b)

    • Example:

        int smallerValue = std::min(3, 6);
      
  15. Min Element:

    • Works: Finds the smallest element in a range.

    • Syntax: std::min_element(first_iterator, last_iterator)

    • Example:

        vector<int> myVector = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
        auto minElement = std::min_element(myVector.begin(), myVector.end());
      
  16. Accumulate:

    • Works: Accumulates the result of an operation on a sequence.

    • Syntax: std::accumulate(first_iterator, last_iterator, initial_value)

    • Example:

        vector<int> myVector = {1, 2, 3, 4, 5};
        int sum = std::accumulate(myVector.begin(), myVector.end(), 0);
      

CODE:

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

int main() {

// Declare a vector of integers

vector<int> myVector = {4, 2, 8, 5, 1, 7, 3, 6};

// Binary search on an ordered sequence

sort(myVector.begin(), myVector.end());

bool found = binary_search(myVector.begin(), myVector.end(), 5);

cout << "Binary search for 5: " << (found ? "Found" : "Not found") << endl;

// Finds a subrange of elements with a given value

auto equalRange = equal_range(myVector.begin(), myVector.end(), 5);

cout << "Equal range for 5: [" << distance(myVector.begin(), equalRange.first) << ", "

<< distance(myVector.begin(), equalRange.second) << ")" << endl;

// Merges two consecutive sorted sequences

inplace_merge(myVector.begin(), myVector.begin() + 4, myVector.end());

cout << "After inplace_merge(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Finds the first occurrence of or the position to insert a specified value

auto lowerBound = lower_bound(myVector.begin(), myVector.end(), 5);

cout << "Lower bound for 5: " << distance(myVector.begin(), lowerBound) << endl;

// Creates a max heap from a sequence

make_heap(myVector.begin(), myVector.end());

cout << "Max heap: ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Merges two sorted sequences

vector<int> anotherVector = {9, 10, 11};

merge(myVector.begin(), myVector.end(), anotherVector.begin(), anotherVector.end(), myVector.begin());

cout << "After merge(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Places elements matching a predicate in the first part

partition(myVector.begin(), myVector.end(), [](int x) { return x % 2 == 0; });

cout << "After partition(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Sorts a sequence

sort(myVector.begin(), myVector.end());

cout << "After sort(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Converts a max heap into a sorted range

sort_heap(myVector.begin(), myVector.end());

cout << "After sort_heap(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Finds the position after the last occurrence of a specified value

auto upperBound = upper_bound(myVector.begin(), myVector.end(), 5);

cout << "Upper bound for 5: " << distance(myVector.begin(), upperBound) << endl;

// Sorts while maintaining the relative order of equal elements

stable_sort(myVector.begin(), myVector.end());

cout << "After stable_sort(): ";

for (auto it : myVector) {

cout << it << " ";

}

cout << endl;

// Returns the greater of two values

int maxVal = max(10, 5);

cout << "Max of 10 and 5: " << maxVal << endl;

// Finds the largest element in a range

auto maxElement = max_element(myVector.begin(), myVector.end());

cout << "Max element: " << *maxElement << endl;

// Returns the smaller of two values

int minVal = min(10, 5);

cout << "Min of 10 and 5: " << minVal << endl;

// Finds the smallest element in a range

auto minElement = min_element(myVector.begin(), myVector.end());

cout << "Min element: " << *minElement << endl;

// Accumulates the result of an operation on a sequence

int sum = accumulate(myVector.begin(), myVector.end(), 0);

cout << "Sum of elements: " << sum << endl;

return 0;

}

OUTPUT:

Binary search for 5: Found
Equal range for 5: [4, 5)
After inplace_merge(): 1 2 3 4 5 6 7 8
Lower bound for 5: 4
Max heap: 8 5 7 4 1 6 3 2
After merge(): 8 5 7 4 1 6 3 2
After partition(): 8 2 6 4 1 7 3 5
After sort(): 1 2 3 4 5 6 7 8
After sort_heap(): 2 3 4 5 6 7 8 1
Upper bound for 5: 4
After stable_sort(): 1 2 3 4 5 6 7 8
Max of 10 and 5: 10
Max element: 8
Min of 10 and 5: 5
Min element: 1
Sum of elements: 36

CONGRATULATION..! NOW YOU ARE THE MASTER OF VECTOR CONTAINER.......!

Did you find this article valuable?

Support AL NAFIS FUAD SHUVO by becoming a sponsor. Any amount is appreciated!

ย