Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array::fill() and array::swap() in C++ STL?
In this section we will see what are the usage of array::fill() and the array::swap() in C++ STL.
The array::fill() function is used to fill the array with some specified value. Let us see one example to get the idea.
Example
#include<iostream>
#include<array>
using namespace std;
main() {
array<int, 10> arr = {00, 11, 22, 33, 44, 55, 66, 77, 88, 99};
cout << "Array elements: ";
for(auto it = arr.begin(); it != arr.end(); it++){
cout << *it << " ";
}
//fill array with 5
arr.fill(5);
cout << "\nArray elements after fill: ";
for(auto it = arr.begin(); it != arr.end(); it++){
cout << *it << " ";
}
}
Output
Array elements: 0 11 22 33 44 55 66 77 88 99 Array elements after fill: 5 5 5 5 5 5 5 5 5 5
The array::swap() function is used to swap the contents of one array to the other array. Let us see one example to get the idea.
Example
#include<iostream>
#include<array>
using namespace std;
main() {
array<int, 10> arr1 = {00, 11, 22, 33, 44, 55, 66, 77, 88, 99};
array<int, 10> arr2 = {85, 41, 23, 65, 74, 02, 51, 74, 98, 22};
cout << "Array1 elements: ";
for(auto it = arr1.begin(); it != arr1.end(); it++){
cout << *it << " ";
}
cout << "\nArray2 elements: ";
for(auto it = arr2.begin(); it != arr2.end(); it++){
cout << *it << " ";
}
//swap array elements
arr1.swap(arr2);
cout << "\nArray1 elements (After swap): ";
for(auto it = arr1.begin(); it != arr1.end(); it++){
cout << *it << " ";
}
cout << "\nArray2 elements (After swap): ";
for(auto it = arr2.begin(); it != arr2.end(); it++){
cout << *it << " ";
}
}
Output
Array1 elements: 0 11 22 33 44 55 66 77 88 99 Array2 elements: 85 41 23 65 74 2 51 74 98 22 Array1 elements (After swap): 85 41 23 65 74 2 51 74 98 22 Array2 elements (After swap): 0 11 22 33 44 55 66 77 88 99
Advertisements