我正在尝试获取迭代器指向的二维数组的最大值。
示例
输入
Data = {{}, {3,11,4}, {1,2}, {5,6}};
输出
max = 11
我有一个二维数组和 max_element
我试图从数组中的值中获取最大值。
使用 1d 迭代器,您可以取消引用迭代器并获取值,即 *iteratorOneD
。但是我怎样才能用 2d 迭代器做这样的事情呢?
我尝试了一些类似的事情。
vector<vector <int>>::iterator position;
position = std::max_element(Data.begin(), Data.end());
int max = *position[0];
cout<< *position << endl;
但是还没有任何效果。我收到此错误。
C2440 "Initialisierung": "std::vector<int,std::allocator>" cant be converted to an int
cout << *position << endl;
的输出是 std::vector(1062256, 1027080)
。
我希望能够将这些值之一分配给 int max
.
最佳答案
您可以在std::max_element
“外部”创建一个迭代器来跟踪迄今为止最大的元素。
int main() {
std::vector<std::vector<int>> Data{{}, {3,11,4}, {1,2}, {5,6}};
// find the first non-empty vector
auto ne = std::find_if(Data.begin(), Data.end(),
[](auto& v) { return !v.empty(); });
if(ne == Data.end()) return 1; // no elements in **any** inner vector
// set the inner iterator to the max element in the first non-empty vector
auto inner = std::max_element(ne->begin(), ne->end());
auto position = std::max_element(ne, Data.end(),
[&inner](auto&, auto& v2) {
if(v2.empty()) return false;
// find the max_element in this inner vector
auto tmp = std::max_element(v2.begin(), v2.end());
// is it greater than the one we had stored
if(*inner < *tmp) {
inner = tmp;
return true;
}
return false;
});
std::cout << "the vector ";
for(auto& col : *position) std::cout << col << ' ';
std::cout << "contains the max element " << *inner << '\n';
}
输出:
the vector 3 11 4 contains the max element 11
关于c++ - 如何获得二维 vector 中所有整数的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67382114/