std::max_element
#include <algorithm> #include <iostream> #include <vector> #include <cmath> static bool abs_compare(int a, int b) { return (std::abs(a) < std::abs(b)); } int main() { std::vector<int> v{ 3, 1, -14, 1, 5, 9 }; std::vector<int>::iterator result; result = std::max_element(v.begin(), v.end()); std::cout << "max element at: " << std::distance(v.begin(), result) << ' '; result = std::max_element(v.begin(), v.end(), abs_compare); std::cout << "max element (absolute) at: " << std::distance(v.begin(), result); }
max element at: 5
max element (absolute) at: 2
std::distance
#include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> v{ 3, 1, 4 }; std::cout << "distance(first, last) = " << std::distance(v.begin(), v.end()) << ' ' << "distance(last, first) = " << std::distance(v.end(), v.begin()) << ' '; }
distance(first, last) = 3
distance(last, first) = -3
std::reverse
#include <vector> #include <iostream> #include <iterator> #include <algorithm> int main() { std::vector<int> v({1,2,3}); std::reverse(std::begin(v), std::end(v)); std::cout << v[0] << v[1] << v[2] << ' '; int a[] = {4, 5, 6, 7}; std::reverse(std::begin(a), std::end(a)); std::cout << a[0] << a[1] << a[2] << a[3] << ' '; }