
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Sorting a vector in C++
Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintains the relative order of equal elements. Quicksort(), mergesort() can also be used, as per requirement.
Algorithm
Begin Decalre v of vector type. Initialize some values into v in array pattern. Print “Elements before sorting”. for (const auto &i: v) print all the values of variable i. Print “Elements after sorting”. Call sort(v.begin(), v.end()) function to sort all the elements of the v vector. for (const auto &i: v) print all the values of variable i. End.
This is a simple example of sorting a vector in c++:
Example
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 }; cout<<"Elements before sorting"<<endl; for (const auto &i: v) cout << i << ' '<<endl; cout<<"Elements after sorting"<<endl; sort(v.begin(), v.end()); for (const auto &i: v) cout << i << ' '<<endl; return 0; }
Output
Elements before sorting 10 9 8 6 7 2 5 1 Elements after sorting 1 2 5 6 7 8 9 10
- Related Articles
- Sorting a vector in descending order in C++
- Sorting a vector of custom objects using C++ STL
- How to append a vector in a vector in C++?
- Sorting a Strings in Java
- Sorting a String in C#
- Sorting a JSON object in JavaScript
- A Pancake Sorting Problem?
- Sorting in C++
- Sorting alphabets within a string in JavaScript
- Structure Sorting in C++
- Alternative Sorting in C++
- Pancake Sorting in C++
- Sorting Arrays in Perl
- Relative sorting in JavaScript
- Extract a data frame column values as a vector by matching a vector in R.

Advertisements