Find a specific tuple element in a vector of tuples?

别等时光非礼了梦想. 提交于 2020-05-08 14:32:05

问题


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?


回答1:


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



回答2:


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; });



回答3:


For C++14 and those that don't wish to torture their eyes.

#include <tuple>
#include <vector>
#include <cstdlib>
#include <algorithm>

using std::get;
using std::tuple;
using std::vector;
using std::find_if;

int main( int, char** )
{
    int needle = 0;
    vector< tuple< int, int, int > > haystack;

    auto position = find_if( haystack.begin( ), haystack.end( ),
                             [ = ]( auto item )
                             {
                                 return get< 0 >( item ) == needle;
                             } );

    if ( position not_eq haystack.end( ) )
        haystack.erase( position );

    return EXIT_SUCCESS;
};


来源:https://stackoverflow.com/questions/37455027/find-a-specific-tuple-element-in-a-vector-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!