gpt4 book ai didi

c++ - 从二维 vector 中找出最小 vector 元素的更好方法

转载 作者:太空狗 更新时间:2023-10-29 23:32:01 25 4
gpt4 key购买 nike

我正在尝试找出最小尺寸的 vector<int>来自 vector<vector<int>> 的元素.

这是我的有效代码,但它对 vector 进行了两次迭代。

#include <iostream>
#include <vector>
#include <limits>

int main()
{
std::vector<std::vector<int>> foo = {{1,2,3,4}, {1,2}, {1,2,3,4,5}, {1,2,3}};
size_t smallestNumElems = std::numeric_limits<size_t>::max();
for (size_t i = 0; i < foo.size(); ++i)
{
const size_t numElems = foo[i].size();
if (smallestNumElems > numElems)
smallestNumElems = numElems;
}
for (size_t i = 0; i < foo.size(); ++i)
{
if (smallestNumElems == foo[i].size())
{
for (size_t j = 0; j < foo[i].size(); ++j)
std::cout << foo[i][j] << '\n';
break;
}
}
}

结果:

1
2
Program ended with exit code: 0

是否有更好的方法来获得相同的结果?

最佳答案

选项 1:

int main()
{
std::vector<std::vector<int>> foo = {{1,2,3,4}, {1,2}, {1,2,3,4,5}, {1,2,3}};
size_t smallestNumElems = std::numeric_limits<size_t>::max();
std::vector<int>* smallestEntry = nullptr; // Store a reference to the smallest entry in here
for (size_t i = 0; i < foo.size(); ++i)
{
const size_t numElems = foo[i].size();
if (smallestNumElems > numElems) {
smallestNumElems = numElems;
smallestEntry = &foo[i];
}
}
for (size_t i = 0; i < smallestEntry->size(); ++i)
std::cout << smallestEntry->at(i) << '\n';
}

选项 2:

#include <algorithm>
// ... Stuff
int main()
{
std::vector<std::vector<int>> foo = {{1,2,3,4}, {1,2}, {1,2,3,4,5}, {1,2,3}};

auto& smallest = *std::min_element(foo.begin(), foo.end(),
[](std::vector<int> const& a, std::vector<int> const& b) { // <- could replace std::vector<int> with auto
return a.size() < b.size();
}
);

for (size_t i = 0; i < smallest.size(); ++i)
std::cout << smallest.at(i) << '\n';
}

关于c++ - 从二维 vector 中找出最小 vector 元素的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56935879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com