C++ STL – vector::at() and vector::swap() with examples

Hello coders! In this tutorial we are going to learn C++ STL – vector::at() and vector::swap().

Vectors are just like dynamic arrays and they have the capability to resize themselves when elements are inserted or deleted from them.


at() is used to point to the object that is present at the parameter of the function.


vectorname.at(index of the element)

C++ Code: Vector::at()

Lets Code It—>

#include <iostream>
#include <vector> //add vector header file
using namespace std;
int main()
   vector<int> numbers; //initialize name of vector as  numbers

    numbers.push_back(9); //push 5 random numbers into the vector





    cout << numbers.at(1); //print the element at position 1 of vector.




Explanation of the above Code

Fisrt we will initialize the name of the as numbers then we have inserted 5 numbers into our vector using push_back function and after that in cout we will use our at function to print the element present at position 1  and the required number will be printed on the screen.

Note: Don’t forget to use vector header file.


swap() function is generally used when we are required to swap two vectors of same type but different sizes.



C++ Code: Vector::swap()

Lets Code It—->

#include <iostream>
#include <vector> //Add vector header file
using namespace std;
 int main()

    vector<int> numbers1{5,7,9,4 }; //vector numbers1 

    vector<int> numbers2{1,2,8,3 }; //vector numbers2

    numbers1.swap(numbers2); //swapping both vectors using vector::swap()

    cout << "numbers1 = "; //cout vector 1

    for (auto it = numbers1.begin();

         it < numbers1.end(); ++it)

        cout << *it << " ";

    cout << endl;

    cout << "numbers2 = ";  //cout vector 2

    for (auto it = numbers2.begin();

         it < numbers2.end(); ++it)

        cout << *it << " ";



numbers1 = 1 2 8 3
numbers2 = 5 7 9 4

Explanation of the above Code

First, we will initialize two vectors numbers1 and numbers2. Then we will write our swap function according to the syntax. After that, we will print vector 1 using cout and auto .begin and the same procedure we will apply for vector 2 and after running the code in the compiler we will notice that the contents of vector 1 ie numbers1 are swapped with vector 2 ie. numbers2 and vice versa.

The same procedure will apply in the case of vectors of different sizes.

Note: Don’t forget to use the vector header file.

Leave a Reply

Your email address will not be published.