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?
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;
}
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With