在元组向量中找到特定的元组元素?

Lam*_*mda 2 c++ tuples vector c++11

我在元组向量中找到元组元素时遇到问题.

我有一个vector<tuple<int,int,int,int>>我需要在向量中找到位置的地方get<0>(vector) = 0.我需要这个位置,因为我需要从该位置的元组中提取其他值.

get<0>是唯一的,并且只会在向量中出现一次.

我怎么做?

Nia*_*all 6

您可以使用该std::find_if算法循环遍历元素并测试所需的条件.

注意 ; 这里的代码假设您要在向量中找到元组的第一个元素为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);
}
Run Code Online (Sandbox Code Playgroud)

std::find_if 上面使用接受谓词的形式;

template< class InputIt, class UnaryPredicate >
  InputIt find_if( InputIt first, InputIt last, UnaryPredicate p );
Run Code Online (Sandbox Code Playgroud)

它返回;

将[迭代器]返回到[first, last)满足特定条件的范围中的第一个元素...


可以使用更简洁的语法,但需要语言支持C++ 14以上,是;

find_if(begin(v), end(v), [](auto&& e) { return get<0>(e) == 0; });
Run Code Online (Sandbox Code Playgroud)


Aru*_*nmu 6

你应该使用std::find_if算法;

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;
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*rst 5

对于 C++14 和那些不想折磨眼睛的人来说。

#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;
};
Run Code Online (Sandbox Code Playgroud)