Q:

Better way to find out smallest sized vector element from 2D vector

I'm trying to find out the smallest sized vector<int> element from vector<vector<int>>.
Here's my code that works but it iterates the vector twice.
#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;
        }
    }
}

Result:
1
2
Program ended with exit code: 0

Is there a better way to get the same result?

A:

Is there a better way to get the same result?

Use the standard library, i.e., std::min_element and customize the comparison by a lamdba.
const auto smallestSizeVec = std::min_element(foo.cbegin(), foo.cend(),
    [](const auto& v1, const auto& v2) { return v1.size() < v2.size(); });

std::cout << "The smallest vector has size " << smallestSizeVec->size() << "\n";

A:

Option 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';
}

Option 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';
}

