C++ comes with a toolbox of ready-made algorithms in <algorithm>. They work on a range given by v.begin() (the start) and v.end() (just past the end).
Sorting and reversing
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {42, 7, 19, 3, 25};
sort(v.begin(), v.end()); // smallest to largest
for (int x : v) cout << x << " ";
cout << "\n";
reverse(v.begin(), v.end()); // flip the order
for (int x : v) cout << x << " ";
cout << "\n";
return 0;
}Output
3 7 19 25 42 42 25 19 7 3
Tip: For largest-to-smallest in one step:
sort(v.begin(), v.end(), greater<int>());
Smallest, largest, count and sum
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
vector<int> v = {4, 8, 15, 16, 23, 42, 8};
cout << "Smallest: " << *min_element(v.begin(), v.end()) << "\n";
cout << "Largest: " << *max_element(v.begin(), v.end()) << "\n";
cout << "How many 8s: " << count(v.begin(), v.end(), 8) << "\n";
cout << "Sum: " << accumulate(v.begin(), v.end(), 0) << "\n";
return 0;
}Output
Smallest: 4 Largest: 42 How many 8s: 2 Sum: 116
min_element and max_element give back the position of the item; the * in front reads the value at that position. (You'll understand why in the Pointers module.)
Is it in there? find
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {5, 10, 15, 20};
auto it = find(v.begin(), v.end(), 15);
if (it != v.end()) {
cout << "Found 15 at index " << (it - v.begin()) << "\n";
}
if (find(v.begin(), v.end(), 99) == v.end()) {
cout << "99 is not in the list\n";
}
return 0;
}Output
Found 15 at index 2 99 is not in the list
Remember: When
finddoesn't find anything, it returnsv.end(). Always compare with it.