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

6
我遇到了在一个元组向量中找到元素的问题。我的向量类型为vector<tuple<int,int,int,int>>,我需要找到其中get<0>(vector) = 0的位置。我需要这个位置,因为我还需要从该位置的元组中提取其他值。 get<0>的值是唯一的,只会在向量中出现一次。如何解决这个问题?
3个回答

13

你应该使用 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;
}

这是因为你使用了自动定位吗?还是其他原因导致的位置问题? - Lamda
它是一个迭代器,如果找到了值,则指向该值,否则指向 v.end(),因此测试条件为 if (it != v.end()) - dkg
@Lamda 作为一般建议,如果您在使用auto时不确定实际类型是什么,请查看上下文。在这里,我将其与'v.end()'进行比较,因此它必须是迭代器。如果仍然不确定,请检查函数的签名:)。我经常听到有关auto使代码不清晰的抱怨,但是如果您知道上下文,情况并不那么糟糕:) - Arunmu
什么是在元组向量中查找给定值的最后一次出现的最简单方法?我尝试将v.begin()和v.end()更改为v.begin()和c.end(),但没有起作用。有什么建议吗? - Croppi

8
你可以使用 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);
}

std::find_if函数使用接受谓词的形式;

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

它会返回:

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


更为简洁的语法,但需要C++14及以上版本的语言支持,是:

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

寻找元组向量中特定值的最后一次出现的最简单方法是什么?我尝试将v.begin()和v.end()更改为v.begin()和c.end(),但没有成功。有什么建议吗? - Croppi
1
@Croppi。听起来你想要倒序搜索,尝试使用rbegin()rend()代替begin()end()。仅仅交换begin和end是不起作用的。 - Niall

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接