Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a specific tuple element in a vector of tuples?

I am having an issue with finding a tuple element, in a vector of tuples.

I have a vector<tuple<int,int,int,int>> in which I need to find the position in the vector where get<0>(vector) = 0. I need the position, as I need to extract the other values from the tuple in that position as well.

The value of get<0> is unique and will only occur once in the vector.

How do I do that?

like image 206
Lamda Avatar asked Nov 29 '22 14:11

Lamda


2 Answers

You should use the std::find_if algorithm;

std::vector<std::tuple<int,int,int,int>> v =
    {{0,1,2,3},{1,2,3,4},{2,3,4,5}};

auto it = std::find_if(v.begin(), v.end(), [](const std::tuple<int,int,int,int>& e) {return std::get<0>(e) == 0;});
if (it != v.end()) {
  std::cout << "Found" << std::endl;
}
like image 103
Arunmu Avatar answered Dec 05 '22 03:12

Arunmu


You can use the std::find_if algorithm to loop over the elements and test for the condition you require.

Note; the code here assumes you want to find the element in the vector where the first element of the tuple is 0.

#include <tuple>
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
    using namespace std;
    vector<tuple<int, int, int, int>> v;
    v.emplace_back(0,1,2,3);
    auto it = find_if(begin(v), end(v), [](decltype(*begin(v)) e) {
        return get<0>(e) == 0;
    });
    if (it != end(v))
        cout << get<0>(*it) << " " << get<1>(*it);
}

std::find_if above uses the form that accepts a predicate;

template< class InputIt, class UnaryPredicate >
  InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );

And it returns;

Returns [an iterator to] the first element in the range [first, last) that satisfies specific criteria...


A more terse syntax that can be used, but requires language support for C++14 onwards, is;

find_if(begin(v), end(v), [](auto&& e) { return get<0>(e) == 0; });
like image 35
Niall Avatar answered Dec 05 '22 04:12

Niall