Finding minimum element of a tuple on the basis of first element

Hello everyone,

I do not know, if it is possible to find the minimum first element in a tuple without using sort function. I have a tuple like this : data=[ ( 23, a, 3.78, d), ( 11, x, 5.8, w)] . I need to obtain the second element which is (11, x, 5.8, w) since 11<23. Is there any way to do it without using sort function ?

Thank you so much in advance.

of course it is. you can iterate all your tuples and keep track of the smallest one via your condition. You don't WANT to sort data to find the lowest element:
iterating each element once and finding the smallest takes N operations.
Sorting, usually, takes at least N(lg(N)) operations, which is only a little more than N for a few items but quite a lot more when you start having many items.


if you only have 2 items, its just a flat compare.
Last edited on
What exactly are a, d, x and w in your tuples? Previously defined variables?

There 3 different ways to access a tuple's elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <tuple>

int main( )
{
   auto tup = std::make_tuple( 11, 'x', 5.8, 'w' );

   // get specific element within a tuple (zero-based)
   std::cout << get<1>( tup ) << '\n';

   // tie tuple values to variables, std::ignore used to discard elements
   char ch;
   std::tie( std::ignore, ch, std::ignore, std::ignore ) = tup;

   std::cout << ch << '\n';

   // C++17 structured binding
   auto [ a, b, c, d ] = tup;

   std::cout << b << '\t' << c << '\n';

   // if x and w are other variables....
   int    x { 42 };
   double w { 8.65 };

   auto tup2 = std::make_tuple( 11, x, 5.8, w );

   std::cout << get<1>( tup2 ) << '\n';
}

http://coliru.stacked-crooked.com/a/08c29256b288faf4

Personally I prefer either direct access to a tuple's element using get or structured binding. I especially like structured binding since using auto means I don't have to know what the types are contained inside the tuple.

Which method I use depends on the circumstances.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <tuple> // https://en.cppreference.com/w/cpp/utility/tuple
#include <vector>

int main( )
{
   std::vector data { std::make_tuple( 23, 'a', 3.78, 'd' ),
                      std::make_tuple( 11, 'x', 5.8, 'w' ) };

   auto [a, b, c, d] = data[0];

   std::cout << c << '\n';
}

http://coliru.stacked-crooked.com/a/9707b1ddc659e291
Thank you so much @jonnin and @George P
I have a tuple like this : data=[ ( 23, a, 3.78, d), ( 11, x, 5.8, w)]


Is data a tuple of 2 elements each being a tuple of 4 elements (ie a tuple of tuples)?
Topic archived. No new replies allowed.