+ 1

How to sort an unsorted set of values using vectors and for loops in C++?

Background: I have a beginner knowledge and experience with vectors, so I know how to use it. Question: Imagine you are given this unsorted set of vectors: vector <int> unsorted = {12, 36, 7, 50, 3, 80, 2}; Explain how I can make this sorted like this output : 2, 3, 7, 12, 36, 50, 80. Please explain your logic and give examples if you can in C++. (Modern version, no std). Thanks. --------------------------------------- Here is my own attempt: (Link) cpp.sh/2kgt

31st Dec 2016, 10:17 AM
Kourosh Azizi
Kourosh Azizi - avatar
7 Antworten
+ 3
#include <algorithm> #include <vector> int main(){ vector<int> v={12,36,7,50,3,80,2}; sort(v.begin(), v.end()); return 0; }
31st Dec 2016, 10:06 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
To output, you use a classical way as this method/function (I'd say function but I am not sure) directly modify your vector It sorts your vector using the classical operator (<) but you can use a function as a parameter (returning a bool of course) or an other object (but I am not sure to understand why and how for this last parameter)
31st Dec 2016, 10:31 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
No, to change the way it sorts, you just add a function as an argument (using the name of the function without "()"). This function return a bool but you can choose how it is decided :)
1st Jan 2017, 1:26 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
Could you please explain sort(v.begin(), v.end()); and what it does ? Also, how can I ouput using this code?
31st Dec 2016, 10:16 AM
Kourosh Azizi
Kourosh Azizi - avatar
+ 1
Ok, yes now this is working. It goes from lowest to biggest elements in the vector. Question: Is it possible to switch the begin () and end () and have it go from biggest to lowest ? Here is the link: cpp.sh/7av6y
31st Dec 2016, 9:47 PM
Kourosh Azizi
Kourosh Azizi - avatar
+ 1
your welcome :)
1st Jan 2017, 12:28 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
Ok, thanks for your information :)
1st Jan 2017, 4:21 AM
Kourosh Azizi
Kourosh Azizi - avatar