Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vector
swap()
c++
communitycreator

What is std::vector::swap in C++?

Sarah Tanveer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The swap() function is defined in the header <vector>. It swaps the contents of two vectors with each other. The sizes of the two vectors may be different.

Syntax

void swap (vector& vec);

Parameters

The function takes one argument:

  • vec: A vector of the same data type with which the content will be swapped.

Return value

This function returns nothing.

The change is made directly to the vector.

Code

#include <iostream>
#include <vector>
using namespace std;
void printVec(int size, vector<char> vec)
{
for(int i = 0; i < size; i++)
{
cout << vec.at(i) << " ";
}
cout << endl;
}
int main() {
vector<char> myVec1 = {'1', '2', '3'};
vector<char> myVec2 = {'a', 'b', 'c', 'd'};
cout << "Vec1, before swap: ";
printVec(myVec1.size(), myVec1);
cout << "Vec2, before swap: ";
printVec(myVec2.size(), myVec2);
myVec1.swap(myVec2);
cout << "Vec1, after swap: ";
printVec(myVec1.size(), myVec1);
cout << "Vec2, after swap: ";
printVec(myVec2.size(), myVec2);
return 0;
}

RELATED TAGS

vector
swap()
c++
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring