find the maximum and minimum value in vector
Let's assume we have a vector of x/y pairs, and we want to find those that have the smallest and largest x
values. We could do this with std::minmax_element
(or std::minmax
, though in this case it's a tiny bit clumsier, IMO), something on this general order:
#include <vector>
#include <algorithm>
#include <iostream>
struct Point {
int x;
int y;
bool operator<(Point const &other) const {
return x < other.x;
}
};
std::vector<Point> points {
{28,13},{48,10},{48,81},{48,54},{48,0},{10,20},
{48,13},{38,10},{58,81},{48,54},{48,0},{40,20},
{18,13},{28,10},{68,81},{48,54},{48,0},{04,20}
};
int main() {
auto pos = std::minmax_element(points.begin(), points.end());
std::cout << "Smallest X: [" << pos.first->x << ", " << pos.first->y << "]\n";
std::cout << "Largest X: [" << pos.second->x << ", " << pos.second->y << "]\n";
}
As an aside, I'd also note that the pair: [04,20]
is all right as it stands, but it should be noted that the leading 0
means that the first number is actually given in octal, not decimal. In this case (single digit less than 8) those are equivalent, but something like 112, 011
(using 0 to fill both out to three digits) would give results that might initially be somewhat surprising (in decimal, the second number is actually 9
, not 11
).
How to get the minimum value within a vector in Rust?
let minValue = vec.iter().min();
match minValue {
Some(min) => println!( "Min value: {}", min ),
None => println!( "Vector is empty" ),
}
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min
fn min(self) -> Option<Self::Item>
where
Self::Item: Ord,
Returns the minimum element of an iterator.
If several elements are equally minimum, the first element is returned. If the iterator is empty, None is returned.
I found this Gist which has some common C#/.NET Linq operations expressed in Swift and Rust, which is handy: https://gist.github.com/leonardo-m/6e9315a57fe9caa893472c2935e9d589
finding the min and max element in vector using std::min_element, std::max_element
i1 = std::max_element(myvector.begin(), myvector.end(), comp1_);
is wrong
i1 = std::max_element(myvector.begin(), myvector.end(), comp2);
would work.
By using comp1_
with max_element
you are effectively asking for the minimum element because max_element finds the element x for which comp1_(x, y) is not true for any y.
You've effectively done a double negative, you've switched to asking for the maximum element but by also reversing the comparison function you've switched to asking for the minimum again.
What you should do when using min_element
and max_element
is pass a comparison function that means 'less than', then these functions will do what they say.
You might now realise that
i2 = std::min_element(myvector.begin(), myvector.end(), comp1_);
would get you the maximum element.
How to get a minimum value from a vector with (value 0)
You can use a custom accumulation like this:
#include <algorithm>
#include <iostream>
#include <vector>
#include <limits> //std::numeric_limits
#include <numeric> //std::accumulate
#include <iterator> //std::begin, std::end
int main()
{
std::vector<int> R{1, 2, 3, 4, 0, -1};
std::cout << std::accumulate(std::begin(R), std::end(R), std::numeric_limits<int>::max(),
[](int a, int b){if (b > 0) return std::min(a, b); return a;});
}
It returns the max for an integer if there are no strictly positive element in the vector.
Finding maximum and minimum in vector of custom data using algorithm
Generally, I would recommend most readable code.
Thus, it would be something like (assuming at least one item):
auto set_minmax = std::minmax_element(begin(data), end(data),
[&](const Speed& a, const Speed& b) { return a.set < b.set; });
auto act_minmax = std::minmax_element(begin(data), end(data),
[&](const Speed& a, const Speed& b) { return a.act < b.act; });
auto min_act_set = std::min(*set_minmax.first, *act_minmax.first);
auto max_act_set = std::max(*set_minmax.second, *act_minmax.second);
However, if the data is really big or the logic is more complex, I would recommend to have an object that accumulate statistics and do some kind of loop over the data.
Find max/min of vector of vectors
Any efficient way to calculate the maximum element in a 2-D array(or vector in your case) involves a complexity of O(n^2)
irrespective of what you do, as the calculation involves a comparison between n*n
elements.Best way in terms of ease of use is to use std::max_element
on the vector of vectors.I will not delve into details.Here is the reference.
How to get the minimum or maximum element in a vector of structures in C++, based on some field in the structure
vector<Size> sizes;
...
vector<Size> sortedByWidths(sizes);
vector<Size> sortedByHeights(sizes);
sort(sortedByWidths.begin(), sortedByWidths.end(),
[](Size s1, Size s2) {return s1.width < s2.width;});
sort(sortedByHeights.begin(), sortedByHeights.end(),
[](Size s1, Size s2) {return s1.height< s2.height;});
Finding the minimum and maximum values in a std::vector of std::pair
You might use std::minmax_element
:
const auto p = std::minmax_element(pairs.begin(), pairs.end());
auto min = p.first->first;
auto max = p.second->first;
displaying minimum and maximum of a vector C++
std::max_element
http://www.cplusplus.com/reference/algorithm/max_element/
std::min_element
http://www.cplusplus.com/reference/algorithm/min_element/
Related Topics
How to Overwrite Only Part of a File in C++
Why How to Call Base Template Class Method from Derived Class
Does Caffe Need Data to Be Shuffled
Write a Recursive Function That Reverses the Input String
How to Handle Key Press Events in C++
How to Solve -------Undefined Reference to '_Chkstk_Ms'-------On Mingw
How to Install Feature Based on the Property Set in Custom Action
Using Boost::Iostreams::Mapped_File_Source with Std::Multimap
Detecting Simulated Keyboard/Mouse Input
Why Do Reference Type Members Cause Implicitly-Declared Copy Assignment Operator to Be Deleted
Why Do Objects Returned from Bind Ignore Extra Arguments
What Is the Vtable Layout and Vtable Pointer Location in C++ Objects in Gcc 3.X and 4.X
Why Doesn't C++ Move Construct Rvalue References by Default
Generate Include File Name in a MACro
What Should Std::Vector::Data() Return If the Vector Is Empty