Skip to content

Commit d8f7f8f

Browse files
authored
[Term Entry] C++ Queue: swap()
* add swap file to cpp terms * add updated swap file to cpp terms * correct terms and cleaned example * add example section with output * newline * minor fixes * Minor changes ---------
1 parent 551e1a0 commit d8f7f8f

File tree

1 file changed

+99
-0
lines changed
  • content/cpp/concepts/queues/terms/swap

1 file changed

+99
-0
lines changed
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
---
2+
Title: '.swap()'
3+
Description: 'Swaps the values of two queues.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Game Development'
7+
Tags:
8+
- 'Classes'
9+
- 'Objects'
10+
- 'OOP'
11+
CatalogContent:
12+
- 'learn-c-plus-plus'
13+
- 'paths/computer-science'
14+
---
15+
16+
In C++, the **`.swap()`** function swaps the values of two queues. The queues must have the same [data type](https://www.codecademy.com/resources/docs/cpp/data-types), although size can differ.
17+
18+
## Syntax
19+
20+
The `.swap()` method can be used with the following syntax:
21+
22+
```pseudo
23+
queue1.swap(queue2);
24+
```
25+
26+
Or alternatively:
27+
28+
```pseudo
29+
swap(queue1, queue2);
30+
```
31+
32+
**Parameters:**
33+
34+
- `queue2`: The other queue whose contents are to be swapped.
35+
36+
**Return value:**
37+
38+
`.swap()` does not return a value.
39+
40+
## Example
41+
42+
This example demonstrates the usage of the `.swap()` method with string queues:
43+
44+
```cpp
45+
#include <iostream>
46+
#include <queue>
47+
using namespace std;
48+
49+
int main() {
50+
// Declare queues
51+
queue<string> hello;
52+
queue<string> world;
53+
54+
// Populate queues
55+
hello.push("hello");
56+
world.push("world");
57+
58+
// Swap the values of the queues
59+
hello.swap(world);
60+
61+
// Print queue values
62+
cout << hello.front() << " " << world.front();
63+
}
64+
```
65+
66+
The expected output would be:
67+
68+
```
69+
world hello
70+
```
71+
72+
## Codebyte Example
73+
74+
The following codebyte example below uses `.swap()` on two integer queues:
75+
76+
```codebyte/cpp
77+
#include <iostream>
78+
#include <queue>
79+
using namespace std;
80+
81+
int main() {
82+
// Declare queues
83+
queue<int> a;
84+
queue<int> b;
85+
86+
// Populate queues
87+
a.push(1);
88+
a.push(2);
89+
b.push(3);
90+
b.push(4);
91+
92+
// Swap the values of a and b
93+
a.swap(b);
94+
95+
// Print queue values
96+
cout << "a: " << a.front() << ", " << a.back() << endl;
97+
cout << "b: " << b.front() << ", " << b.back();
98+
}
99+
```

0 commit comments

Comments
 (0)