自己编写外循环可能最简单:
if (matrix.size() == 0 || matrix[0].size() == 0) {
// matrix is empty, handle special case
throw std::logic_error("empty");
}
int best = matrix[0][0];
size_t rowidx = 0, colidx = 0;
for (auto it = matrix.begin(); it != matrix.end(); ++it) {
auto maxit = max_element(it->begin(), it->end());
if (*maxit > best) {
best = *maxit;
rowidx = it - matrix.begin();
colidx = maxit - it->begin();
}
}
或者,您可以编写一个迭代整个矩阵的迭代器类:
struct MatrixIterator : std::iterator<std::forward_iterator_tag, int> {
typedef vector<vector<int> > Matrix;
Matrix &m;
size_t rowidx, colidx;
explicit MatrixIterator(Matrix &m, size_t row = 0, size_t col = 0) : m(m), rowidx(row), colidx(col) {};
int &operator*() { return m[rowidx][colidx]; }
MatrixIterator &operator++() {
++colidx;
if (colidx == m[rowidx].size()) {
colidx = 0;
++rowidx;
}
return *this;
}
MatrixIterator operator++(int) {
MatrixIterator result = *this;
++*this;
return result;
}
bool operator==(const MatrixIterator &rhs) {
return rowidx == rhs.rowidx && colidx == rhs.colidx;
}
bool operator!=(const MatrixIterator &rhs) {
return ! (*this == rhs);
}
static MaxtrixIterator end(Matrix &m) {
return MatrixIterator(m, m.size() - 1, m.back().size());
}
};
现在你可以这样做:
MatrixIterator result = std::max_element(MatrixIterator(m), MatrixIterator::end(m));
size_t rowidx = result.rowidx, colidx = result.colidx;