C++ 查找两个向量之间的最大元素

C++ 查找两个向量之间的最大元素,c++,C++,我原以为下面的方法行得通,但它只输出零。想法 std::vector<int> a = { 1, 2, 3 }; std::vector<int> b = { 4, 5, 6 }; int max = *std::max(std::max(a.begin(), a.end()), std::max(b.begin(), b.end())); std::cout << max; std::vector a={1,2,3}; 向量b={4,5,6}; int

我原以为下面的方法行得通,但它只输出零。想法

std::vector<int> a = { 1, 2, 3 };
std::vector<int> b = { 4, 5, 6 };

int max = *std::max(std::max(a.begin(), a.end()), std::max(b.begin(), b.end()));
std::cout << max;
std::vector a={1,2,3};
向量b={4,5,6};
int max=*std::max(std::max(a.begin(),a.end()),std::max(b.begin(),b.end());
您正在使用的std::cout比较其参数。也就是说,它返回两个迭代器中较大的一个

内部调用所需的是,它在一个范围内查找最大元素:

std::vector<int> a = { 1, 2, 3 };
std::vector<int> b = { 4, 5, 6 };

int max = std::max(*std::max_element(a.begin(), a.end()), *std::max_element(b.begin(), b.end()));
std::cout << max;
std::vector a={1,2,3};
向量b={4,5,6};
int max=std::max(*std::max_元素(a.begin(),a.end()),*std::max_元素(b.begin(),b.end());
标准::cout

这将找到单个向量最大值的最大值。例如,对于第一个向量,{1,2,3},最大值为3,对于第二个向量,{4,5,6},最大值为6,最大值为3和6,现在为6

这是一种在空范围内表现合理的方法。如果其中一个范围为空,您仍然可以从另一个范围获得最大值。如果两个范围都为空,则得到
INT\u MIN

int m = std::accumulate(begin(b), end(b),
             std::accumulate(begin(a), end(a), INT_MIN, std::max<int>),
             std::max<int>);
int m=std::累加(开始(b),结束(b),
标准::累积(开始(a),结束(a),最小整数,标准::最大值),
标准:最大值);

std::accumulate
在这里更好,因为您需要的是一个值,而不是迭代器。

请阅读
std::max
的文档。它不需要射程。请看一看。@Joseph伟大的资源@USSR4194178我仍然认为CPULIST是我在堆栈溢出中学到的最重要的东西之一。在这个例子中,这不是问题,在确定迭代器之前,需要确保范围是非空的。
int m = std::accumulate(begin(b), end(b),
             std::accumulate(begin(a), end(a), INT_MIN, std::max<int>),
             std::max<int>);