您可以使用该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 上面使用接受谓词的形式;
Run Code Online (Sandbox Code Playgroud)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; });
Run Code Online (Sandbox Code Playgroud)
你应该使用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)
对于 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)