What is a Tuple, a Pairs and a Tie in C++

Share the Article

What are Tuples?

In C++ language, the classes work as user defined data types. The class contains both data and function together. Therefore, to make the data more and more organized, C++11 has introduced a new concept of tuple. Tuples give very good flexibility for creating a collection of different or same data types.

In a class, we can access a data member or function using its name. However, in a tuple we use get<index> helper function for the same. Undoubtedly, in Object Oriented programming, the Tuple concept provides much more power for creating and handling multiple user defined data.

Header file required


How to define tuple data type

std::tuple<int,int> t1 (5,5); // t1 tuple holding 2 int values std::tuple<int,char,float>t2(5,'a',34.3); // t2 tuple holding int, char and float values std::tuple<char,string,float>t3('a',"MainFunda".23.80); // t3 tuple holding char, string and float

Basic Example of tuple in C++

Lets us create a Sample application for seeing how to set and get data from tuples

#include <iostream> //Main header file #include <string> // for string #include <tuple> //for tuple using namespace std; int main() { std::tuple<int, float, char,std::string> t1 (5,23.8,'a',"MainFunda"); //created tuple holding 4 data values int iData = std::get < 0 > (t1); // get 1st int value float fData= std::get < 1 > (t1); // get 2nd float value char cData = std::get<2>(t1); // get 3rd char vaue std::string strData = std::get < 3 > (t1); // get 3rd char value cout <<"Int is "<< iData <<"\nFloat is "<<fData <<"\nChar is "<<cData <<"\nString is "<<strData <<endl; return 0; }

As seen above getting data from a tuple object is very easy . We just need to call get<index-1> for knowing the content of data from tuple.

output of code using a tuple in c++

Error scenario with invalid get<index>

Lets see one more application where we are calling get<index-1> with invalid index

#include <iostream> //Main header file #include <string> // for string #include <tuple> //for tuple using namespace std; int main() { std::tuple<int, float, char,std::string> t1 (5,23.8,'a',"MainFunda"); //created tuple holding 4 data values int iData = std::get < 5 > (t1); // get 5th (invalid) value cout <<"Int is "<< iData <<endl; return 0; }

We are getting compile time error for accessing invalid index for tuple. This is the advantage of tuple .

compiler error on using wrong index in std:;get(index) with tuples

Tuple – Helper Function

get( )

The function get( ) takes an integer index as input and returns the reference to tuple data member at that index . In turn, we can use such reference for setting a tuple data member also. Below application demonstrates this

#include <iostream> //Main header file #include <string> // for string #include <tuple> //for tuple using namespace std; int main() { std::tuple<int, float, char,std::string> t1 (5,23.8,'a',"MainFunda"); //created tuple holding 4 data values int iData = std::get < 0 > (t1); // get first data member of tuple cout <<"Int is "<< iData <<endl; std::get<0>(t1) = 30; // set first data member of tuple iData = std::get<0>(t1); cout <<"Int after modification " << iData <<endl; return 0; }


output of code demonstrating get( ) function with tuple

tuple_size( )

At any time we can get the size of tuple by using tuple_size( ) function.

#include <iostream> // main header #include <tuple> // tuple header #include<string> // string header using namespace std; int main () { std::tuple<int,char,float,std::string> t1 (1,'a',1.1,"MainFunda"); cout << "size of tuple is " <<std::tuple_size<decltype(t1)>::value << endl; // value contain the number of elements return 0; }


output of code using tuple_size( ) function

make_tuple( )

The function make_tuple( ) is used for creating a tuple from a list of elements passed in the arguments. List of elements which we are passing as argument can be of different data types.

#include <iostream> //main header #include <tuple> // for tuple using namespace std; int main() { auto t1 = std::make_tuple(1,2.4, "MainFunda"); // tuple creation cout << "The value of t1 is " << std::get<0>(t1) << ", " << std::get<1>(t1) << ", " << std::get<2>(t1) <<endl; }


output of code using make_tuple( ) function

forward_as_tuple( )

The function forward_as_tuple( ) creates a temporary tuple as r-value reference from argument passed as parameter to this function.

// forward_as_tuple example #include <iostream> // main header #include <tuple> // for tuple using namespace std; void show_Data(std::tuple<int&&, int&&> t1) { std::cout << std::get<0>(t1) << ", " << std::get<1>(t1) << endl; } int main() { show_Data (std::forward_as_tuple(30,30)); return 0; }


output of code using forward_as_tuple( ) function for forwarding a tuple in c++

tuple_cat( )

The function tuple_cat( ) concatenates two or more tuples which are passed as the arguments.

#include <iostream> //main header #include <string> // for string #include <tuple> // for tuple using namespace std; int main () { std::tuple<char,std::string> t1 ('c',"MainFunda"); std::pair<int,float> t2 (100,12.5); auto t3 = std::tuple_cat ( t1, t2 ); std::cout << "ConCat T3" <<endl ; std::cout << std::get<0>(t3) << endl; std::cout << std::get<1>(t3) << endl; std::cout << std::get<2>(t3) << endl; std::cout << std::get<3>(t3) << endl; auto t4 = std::tuple_cat(t3, std::make_tuple(" test", "begin")); std::cout << "ConCat T4" <<endl ; std::cout << std::get<0>(t4) << endl; std::cout << std::get<1>(t4) << endl; std::cout << std::get<2>(t4) << endl; std::cout << std::get<3>(t4) << endl; std::cout << std::get<4>(t4) << endl; std::cout << std::get<5>(t4) << endl; return 0; }


output of code using tuple_cat( ) function

What are Pairs in C++?

Pairs creates class template from 2 different or same datatypes . It is a specialized version of tuple with 2 elements.

Header File required for pairs

#include <utility>

Basic example of Pairs

lets see below simple example for creating and displaying the Pair content

#include <iostream> // main header #include <utility> // for pair using namespace std; int main () { std::pair <int,float> p1 (1,2); std::cout << "foo: " << p1.first << ", " << p1.second << endl; return 0; }


basic example of using std::pairs< >

Pair-Helper Functions

make_pair( )

This function creates a pair object from its first and second argument.

#include <iostream> // main header #include <utility> // for pair using namespace std; int main () { std::pair <int,float> p1 = make_pair(1,2); std::cout << "foo: " << p1.first << ", " << p1.second << endl; return 0; }


output of basic example with make_pair( ) function

What is a Tie of in C++?

We have read tuple data types above. A tie creates an L-vlaue tuple for future use. Tie is mainly used for extracting element from tuple.

Basic Example with Tie

// packing/unpacking tuples #include <iostream> // std::cout #include <tuple> // std::tuple, std::make_tuple, std::tie int main () { int i1; float f1; std::tuple<int,float> t1 = std::make_tuple (1, 22.3); // packing values into tuple std::tie (i1,f1) = t1; //unpacking tuple into variables std::cout << "1st element " << i1 << '\n'; std::cout << "2nd element: " << f1 << '\n'; //example to ignore some element std::tie (i1, std::ignore) = t1; // unpacking tuple into variables //and ignoring 2ns element std::cout << "1st element " << i1 << '\n'; return 0; }


output of code using std::tie< >

Main Funda: Tuples provides additional flexibility to play around with user-defined data types

Related Topics:

Lambda in C++11
Lambda in C++17
What are the drawbacks of using enum ?
Which member functions are generated by compiler in class?
C++ Multithreading: Understanding Threads
How to stop compiler from generating special member functions?
Compiler Generated Destructor is always non-virtual
How to make a class object un-copyable?
Why virtual functions should not be called in constructor & destructor ?
Explaining C++ casts
How std::forward( ) works?
Rule of Three
How std::move() function works?
What is reference collapsing?
How delete keyword can be used to filter polymorphism
emplace_back vs push_back

Share the Article

2,736 thoughts on “What is a Tuple, a Pairs and a Tie in C++

  1. Bitcoin Cash Bitcoin is practically the king of cryptocurrencies, without which it is difficult to imagine such a combination.Bitcoin SV is clear in its plans and roadmap to build a stable protocol moulded along the likes of TCP/IP to bring certainty for enterprises, users, and stakeholders wishing to make use or implement blockchain-based technologies.Encontre a pagina a qual deseja adicionar a calculadora, va para o modo de edicao, clique em ‘Texto’ e cole o codigo nela. https://www.jmenjoymadrid.com/forum/foro-de-viajes/bitspincasino-espelho-brazil BitSpinCasino espelho Brazil At the moment, only a select group of crypto casinos accept crypto as a payment method.A extrusao e uma preocupacao para vedacoes radiais onde existe uma lacuna projetada entre os componentes moveis: o pistao e o orificio ou a haste e o orificio.Bitcoin uses the Proof-of-Work (PoW) consensus mechanism.All games and features are fully accessible on the go.Game – Nossa escolha para o melhor cassino de Bitcoin dos EUA 2.MyBookie has been active since 2014, and sports bettors flock here primarily because of its vast online sports betting market and prop bet options.Ainda nao entramos nesta area (retangulo vermelho) que mostra que estamos em um mercado de sobrecompra”.Outros conseguem construir uma reputacao por meio de recomendacoes ou conteudo exclusivo.Para finalizar, o processo de ativacao do minerador e tao simples quanto apertar um botao.

  2. Many of the casinos we have reviewed have also decided to provide you with greater bonuses than their standard welcome bonuses.Depois de se registrar completamente, faca login em sua conta e clique na guia subconta.It detracts from value (I gather there are about 5,800 altcoins as of today)”. https://www.brentallenproperties.com/forum/general-discussions/maquina-de-ranhura-para-bitcoin-re-di-roma MГЎquina de ranhura para bitcoin re di roma You will need to deposit at least five mBTC (about USD 1); you can increase that if you want more free play money (but no more than 250 mBTC).O casino tem grandes bonus de deposito, no entanto, eles sao validos apenas por 7 dias.The internet’s first cryptocurrency also gained some notoriety after the People’s Bank of China prohibited Chinese financial institutions from transacting in Bitcoins.While no dedicated app is available, mBit features loads of instant-play games that allow you to play the majority of the casino games in the catalog straight from your mobile browser.How Much is Bitcoin Worth in Gold.We’ve compiled a list of the best ones (according to us, and the public) that you can find below.Hot Triple Sevens : Hot Triple Sevens is an exciting avenue for crypto gamblers to explore and enjoy.We invite you to use our commenting platform to engage in insightful conversations about issues in our community.That’s because for many years, Bitcoins weren’t worth anything.

  3. Therefore, the online casino site has a swift and easy banking system that allows transactions in Bitcoin.Como funcionam os cassinos Bitcoin?Bitcoins lowest price after its all time high in 2017 was around $3,350. https://www.fairislemaritimeconsultancy.com/forum/education-forum/roleta-do-bitcoin-cassino-bitcoin-50-cm Roleta do bitcoin cassino bitcoin 50 cm Evite utilizar cartoes com espessura superior a 2,1 mm, pois podem danificar a ranhura para cartoes SD se tentar inseri-los.Sports Market Range: 4/5.Previsao do Bitcoin na segunda-feira, 5 de Dezembro: preco e 84893 R$, maxima e 90836 R$, minima e 78950 R$.Para oferecer o melhor servico aos nossos clientes, temos uma equipe treinada e especializada na manutencao de maquinas de ranhura Rogroover e contamos com um corpo de funcionarios altamente qualificado tanto na locacao, quanto na manutencao da maquina de ranhura Rogroover.They are a kind of promotion that most casino sites will run, and allow you to take advantage of during your first deposit.TomyGame is a bitcoin-based game to discover and play a lot of Mini Games inside.Qualquer pessoa com Bitcoin em sua posse pode se tornar um alvo criminoso, principalmente considerando que o Bitcoin e menos como acoes e mais como dinheiro.O primeiro usuario a enviar a resposta correta usuario, recebe um premio em dinheiro.Uma vez que voce ja tenha uma carteira, voce recebera dinheiro virtual na forma de Tether, Bitcoin, Binance Coin ou outra criptomoeda, dependendo do corretor escolhido.

  4. This action of bumetanide in resistance arteries is the likely mechanism for its hypotensive effect valtrex overnight delivery Darien added, If patients feel like they re prepared to make decisions and there is true shared decision making, they are less likely to have decisional regret about not pursuing more aggressive treatments

  5. The percentage of women with a history of estrogen use was nonsignificantly lower for women who developed dementia than for those who developed mild cognitive impairment or who were cognitively normal furosemide After 6 days or so, i could feel what felt like the lump was breaking up behind my nipple

  6. pamabrom vs lasix Pain or tenderness in the breast or nipple A lump in the breast A lump in the lymph nodes underneath the armpit Lymph node tenderness Dimpling or thickening of the skin of the breast A sore on the nipple or breast Nipple discharge Change in nipple appearance Discoloration of nipple

  7. cialis allopurinol 300 heumann nicht lieferbar Herman added that despite such meetings, It s not clearyet that the White House appreciates the need to scale backthese surveillance programs substantially instead of justrationalizing or tinkering with them buy stromectol without prescription Incident ischemic heart disease in the younger age group was observed in 4

  8. Pingback: 3necessarily
  9. What is doxycycline mainly used for? Doxycycline is a tetracycline antibiotic. This medication is used to treat a wide variety of bacterial infections, including those that cause acne.It works by slowing the growth of bacteria. Slowing bacteria’s growth allows the body’s immune system to destroy the bacteria. Doxycycline may treat: syphilis, acute gonococcal urethritis, pharyngitis, cholera and more. Doxycycline is also used to prevent malaria.
    Special offer: buy doxycycline online only for $0.34 per pill, save up to $311.56 and get discount for all purchased!
    Two Free Pills (Viagra or Cialis or Levitra) available With Every Order. No Prescription Required, safe & secure payments.

  10. Hey there! I’ve been reading your blog for a long time now and finally got the
    courage to go ahead and give you a shout out from
    Lubbock Texas! Just wanted to say keep up the good work!

  11. I absolutely love your site.. Very nice colors & theme. Did you build this website yourself? Please reply back as I’m attempting to create my own blog and would like to find out where you got this from or just what the theme is called. Thanks.

  12. A motivating discussion is worth comment. I think that you ought to write more on this subject matter, it may not be a taboo matter but generally people don’t speak about these issues. To the next! Kind regards.

  13. Simply wanna input on few general things, The website layout is perfect, the subject matter is rattling excellent. “I delight in men over seventy. They always offer one the devotion of a lifetime.” by Oscar Fingall O’Flahertie Wills Wilde.

  14. Any substance that inhibits the growth and replication of a bacterium or kills it outright can be called an antibiotic. Antibiotics are a type of antimicrobial designed to target bacterial infections within (or on) the body. Antibiotics are used to treat bacterial infections. Some are highly specialised and are only effective against certain bacteria. Others, known as broad-spectrum antibiotics, attack a wide range of bacteria, including ones that are beneficial to us.
    Special offer: buy antibiotics online – https://centaur.ag/wp-content/uploads/wpc247/antibiotics/ and get discount for all purchased!
    Two Free Pills (Viagra or Cialis or Levitra) available With Every Order.
    No Prescription Required. Safe & Secure Payments. Fast & Free Delivery.
    Tags: antibiotics buy, get online antibiotics no prescription, antibiotics in order online

  15. You really make it seem really easy along with your presentation however I find this matter to be really one thing which I think I’d never understand. It seems too complex and very vast for me. I’m looking ahead on your next put up, I will attempt to get the cling of it!

  16. Aw, this was an extremely nice post. Spending some time and actual effort to make a superb article… but what can I say… I put things off a whole lot and never manage to get anything done.

  17. Обикновено 3-звездните хотели в Ораниестад струват ₤ 88 на вечер, а 4-звездните курорти в Ораньестад са ₤ 631 на вечер.

    Here is my blog post Emery

  18. Първите европейци, които посещават Аруба, са Америго Веспучи, а също и Алонсо де Охеда през 1499 г., който утвърждава острова за Испания.

    Visit my homepage :: Kathi

  19. There are many things to do in Las Vegas and one of the most popular is to gamble. The casinos are some of the most visited sites when people travel to the city, along with museums, parks, shopping and more. Visit the Vegas Strip and you will find luxurious resorts like Caesars Palace, Bellagio, MGM Grand and Treasure Island. Or visit downtown for great dining at restaurants such as Paris Las Vegas or Bistro by Hubert Keller, or simply walk around to see all that Sin City has to offer.

  20. A motivating discussion is definitely worth comment. I do think that you ought to publish more on this subject, it might not be a taboo subject but typically people do not speak about these subjects. To the next! Kind regards.

  21. The very next time I read a blog, I hope that it doesn’t disappoint me as much as this one. I mean, Yes, it was my choice to read through, nonetheless I genuinely believed you would probably have something helpful to talk about. All I hear is a bunch of crying about something that you could fix if you weren’t too busy looking for attention.

  22. This is a really good tip especially to those fresh to the blogosphere. Short but very accurate information… Appreciate your sharing this one. A must read post.

  23. An interesting discussion is definitely worth comment. There’s no doubt that that you ought to publish more about this issue, it might not be a taboo subject but usually people do not discuss these issues. To the next! Cheers!