我遇到了在元组向量中找到元组元素的问题。
我有一个vector<tuple<int,int,int,int>>
,我需要在get<0>(vector) = 0
向量中找到位置。我需要这个位置,因为我需要从该位置的元组中提取其他值。
get<0>
的值是唯一的,并且只会在向量中出现一次。
我该怎么做?
答案 0 :(得分: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);
}
上面的 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; });
答案 1 :(得分:5)
您应该使用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;
}
答案 2 :(得分:2)
对于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;
};