Interesting problem.
It is easy to do this for rows. For columns it is harder. Someone might have a better solution, but one possibility is to use custom predicates:
Code:
#include <iostream>
#include <iomanip>
#include <vector>
#include <cstdlib>
struct compare_nth
{
const unsigned n;
compare_nth(unsigned num): n(num) {}
/*
note: it is programmers responsibility to ensure than first[n] and second[n]
are not out of range
*/
template <class Container>
bool operator() (const Container& first, const Container& second)
{
return first[n] < second[n];
}
};
int main()
{
typedef std::vector<int> IntLine;
typedef std::vector<IntLine> IntTable;
IntTable table;
for (int i = 0; i != 10; ++i) {
IntLine line;
for (int j = 0; j != 6; ++j) {
line.push_back(rand());
std::cout << std::setw(7) << line.back();
}
table.push_back(line);
std::cout << '\n';
}
//simple to find in rows:
std::cout << "\nmin in rows:";
for (IntTable::iterator line_it = table.begin(); line_it != table.end(); ++line_it) {
std::cout << ' ' << *std::min_element(line_it->begin(), line_it->end());
}
//harder to find in columns
//NB! assumes all rows have same length
std::cout << "\nmin in columns:";
for (unsigned i = 0; i != table[0].size(); ++i) {
std::cout << ' ' << (*std::min_element(table.begin(), table.end(), compare_nth(i)))[i];
}
}
However, if boost::lambda is available to you, you won't need compare_nth and could search columns like this:
Code:
std::cout << ' ' << (*std::min_element(table.begin(), table.end(), _1[i] < _2[i]))[i];
Basically, you'll need to keep your head clear as to what dereferences to what.