+ 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
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;
}
+ 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)
+ 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 :)
+ 1
Could you please explain sort(v.begin(), v.end()); and what it does ? Also, how can I ouput using this code?
+ 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
+ 1
your welcome :)
0
Ok, thanks for your information :)