如果我们定义一个包含整数的向量向量,那么我们用一些数据填充它,最好的方法是使用max_element算法来找到最大的int?
答案 0 :(得分:2)
最佳方式是什么意思?时间复杂度始终为O(n*m)
。不同的实现之间没有太大区别。如下所示的简单实现就足够了。
#include <vector>
#include <limits>
using namespace std;
int main()
{
vector<vector<int> > vec;
int res = numeric_limits<int>::min();
for (auto i = vec.begin(); i != vec.end(); ++i) {
auto t = max_element(i->begin(), i->end());
if (t != i->end() && *t > res)
res = *t;
}
cout << res << endl;
}
答案 1 :(得分:2)
如何收集内部载体&#39;首先将maxima转换为单独的向量:
vector<vector<int>> outer = ...;
vector<int> localMaxElements;
for (const auto& inner : outer) {
localMaxElements.push_back(*max_element(inner.begin(), inner.end()));
}
// your final max element:
return max_element(localMaxElements.begin(), localMaxElements.end());
您还可以在内部向量上使用max_element
:
auto finalMax = max_element(outer.begin(), outer.end(),
[](const vector<int>& a, const vector<int>& b) {
return max_element(a.begin(), a.end()) < max_element(b.begin(), b.end());
}
);
但另一种方式(或者gongzhitaao提出的解决方案)很可能会更快。
答案 2 :(得分:0)
// ForEach.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ctime>
struct FindMaxOfAll
{
public:
FindMaxOfAll() : maxOfAll(0) {}
void operator()(std::vector<int>& cont)
{
int max = *(std::max_element(cont.begin(), cont.end()));
if(max > maxOfAll) { maxOfAll = max; }
}
int getMaxOfAll() { return maxOfAll; }
private:
int maxOfAll;
};
int main()
{
// fill containers with data
srand (time(NULL));
std::vector<std::vector<int> > values2d(5); //create 10 vectors of integers, all empty
std::for_each(values2d.begin(), values2d.end(),
[](std::vector<int>& cont) { cont.resize(5); std::generate ( cont.begin(), cont.end(), rand); });
std::ostream_iterator<int> out_it (std::cout,", ");
std::for_each(values2d.begin(), values2d.end(),
[&](std::vector<int>& cont) { std::copy ( cont.begin(), cont.end(), out_it ); });
// Find the max of all
FindMaxOfAll maxOfAll = std::for_each(values2d.begin(), values2d.end(), FindMaxOfAll());
std::cout << "\n\nthe max of all is " << maxOfAll.getMaxOfAll() << std::endl;
return 0;
}
这是我的答案。我更详细,但也包括我如何初始化向量。这是我已经发现的一件事,即for_each可以是有用的,因为它实际上可以维护和返回函子的状态,这允许你做一些像积累信息的事情。它是最好的吗?谁知道?什么是最好的?最快的?最少的代码行?最容易理解?这是非常主观的。由于提问者有99k代表,我想也许它毕竟不是家庭作业。看到人们解决它的不同方式似乎是一个有趣,快速的挑战。