maximum and minimum value?
I have made a matrix using vector and iterator, how c开发者_Python百科an I find maximum and minimum value from it. It is something like:
vector<int> > matrixes(10);
typedef std::vector<std::vector<int> >::iterator it;
it rows = matrixes.begin();
if (rows->size() == 10)
++rows;
rows->push_back(res);
}
for(size_t q=0; q < matrixes.size(); ++q)
{
for(size_t r=0; q < matrixes[q].size(); ++r)
cout << matrixes[q][r] << " ";
cout << endl;
}
I want to find maximum and minimum value through it, how is it possible?
Use std::max_element and std::min_element in the STL.
If you have an std::vector, you can do
std::vector<int> my_vector;
//Populate vector
int max = std::max_element( my_vector.begin(), my_vector.end() );
See the reference.
Just add two variables to hold the maximum and minimum value. Update the portion where you display it.
vector<int> > matrixes(10);
typedef std::vector<std::vector<int> >::iterator it;
it rows = matrixes.begin();
int maxVal,minVal;
if ( matrixes.size() > 0 && matrixes[0].size() > 0 )
maxVal = minVal = matrixes[0][0];
for(size_t q=0; q < matrixes.size(); ++q)
{
for(size_t r=0; q < matrixes[q].size(); ++r)
{
cout << matrixes[q][r] << " ";
cout << endl;
// update min, max here
maxVal= maxVal<matrixes[q][r]?matrixes[q][r]:maxVal;
minVal= minVal>matrixes[q][r]?matrixes[q][r]:minVal;
}
}
std::sort( matrixes.begin(), matrixes.end() );
First element in vector will be the least and the last element will be greatest.
精彩评论