TheAlgorithms-C-Plus-Plus/others/vector_important_functions.cpp

44 lines
1.2 KiB
C++
Raw Normal View History

2020-05-29 03:55:46 +08:00
/**
* @file
* @brief A C++ program to demonstrate working of std::sort(), std::reverse()
*/
2018-10-03 01:46:58 +08:00
#include <algorithm>
#include <iostream>
2020-05-29 03:55:46 +08:00
#include <numeric> // For accumulate operation
2018-10-03 01:46:58 +08:00
#include <vector>
2020-05-29 03:55:46 +08:00
/** Main function */
int main() {
// Initializing vector with array values
int arr[] = {10, 20, 5, 23, 42, 15};
int n = sizeof(arr) / sizeof(arr[0]);
std::vector<int> vect(arr, arr + n);
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
std::cout << "Vector is: ";
for (int i = 0; i < n; i++) std::cout << vect[i] << " ";
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
// Sorting the Vector in Ascending order
std::sort(vect.begin(), vect.end());
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
std::cout << "\nVector after sorting is: ";
for (int i = 0; i < n; i++) std::cout << vect[i] << " ";
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
// Reversing the Vector
std::reverse(vect.begin(), vect.end());
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
std::cout << "\nVector after reversing is: ";
for (int i = 0; i < 6; i++) std::cout << vect[i] << " ";
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
std::cout << "\nMaximum element of vector is: ";
std::cout << *max_element(vect.begin(), vect.end());
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
std::cout << "\nMinimum element of vector is: ";
std::cout << *min_element(vect.begin(), vect.end());
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
// Starting the summation from 0
std::cout << "\nThe summation of vector elements is: ";
std::cout << accumulate(vect.begin(), vect.end(), 0);
2018-10-03 01:46:58 +08:00
2020-05-29 03:55:46 +08:00
return 0;
2018-10-03 01:46:58 +08:00
}