【发布时间】:2014-04-29 15:19:00
【问题描述】:
如果我们定义一个包含整数的向量向量,然后用一些数据填充它,那么使用 max_element 算法找到最大整数的最佳方法是什么?
【问题讨论】:
如果我们定义一个包含整数的向量向量,然后用一些数据填充它,那么使用 max_element 算法找到最大整数的最佳方法是什么?
【问题讨论】:
最好的方法是什么意思?时间复杂度始终为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;
}
【讨论】:
如何先将内部向量的最大值收集到一个单独的向量中:
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());
}
);
但另一种方式(或公知淘提出的解决方案)很可能会更快。
【讨论】:
// 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 代表,我想也许这毕竟不是家庭作业。看看人们解决问题的不同方法似乎是一个有趣、快速的挑战。
【讨论】:
cout 上使用ostream_iterator 非常棒!谢谢你,我从来没有想过!