How to work and using function with vector<vector<>> in C++?

79 views Asked by At

I'm a student and I'm using c++. In the time I learn online I can't find detail about how vector<vector<>> works.

I want to ask how to use function like count(), find() for this type of vector?

Such as I have a vector<vector<int>> v= [[1,3],[2,3]] how can I using count to count how many 3 in all the vector or to find the first vector that have 3.

I new so maybe my question hard to understand, thank you for reading.

When I try this:

find(v.begin() , v.end(),{v[0][1]} or find(v.begin() , v.end(),v[0][1])

it gives an error.

1

There are 1 answers

3
Pepijn Kramer On

This is a solution without loops, like you seem to be needing. Note the accumulate_threes_in_a_vector could also have been a lambda

#include <cassert>
#include <vector>
#include <algorithm>
#include <numeric>

// a function that adds the number of 3s in a vector to a sum
auto accumulate_threes_in_a_vector(std::size_t sum, const std::vector<int>& values)
{
    // https://en.cppreference.com/w/cpp/algorithm/count
    // loop over the int vector and add the number of 3's
    return sum += std::count(values.begin(), values.end(), 3);
}

int main()
{
    std::vector<std::vector<int>> vector_of_vectors{
        {1, 2, 3}, 
        {3, 4, 3, 3},
        {3, 3}
    };

    // https://en.cppreference.com/w/cpp/algorithm/accumulate
    // sum the number of 3s in the vector of vectors
    auto total = std::accumulate(vector_of_vectors.begin(), vector_of_vectors.end(), 0, accumulate_threes_in_a_vector);
    
    return total;
}