Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we hold 2 data types in a STL list?

Tags:

c++

list

stl

i want my list to hold an integer value as well as a string value. is this possible?
I am implementing a hash table using STL lists which can store only the integer. I am hashing a string to get the index where i am storing my integer. Now i want my string to be stored with the integer as well.

EDIT 1:
so i am using this statement:

    list<pair<int,string>> table[127];    

and here is the error im getting:
>>' should be> >' within a nested template argument list ok i fixed this.. it seems i didn't put a space in the ">>" so now its fix

next question
how do i add my pair to the table array?

like image 523
otaku Avatar asked Sep 13 '13 06:09

otaku


Video Answer


3 Answers

You can have a list of std::pairs or, with c++11, std::tuple, for example:

std::list < std::pair< int, std::string > >list;
std::list < std::tuple< int, std::string > >list;

To access the elements inside a pair, use pair.first and pair.second. To access the elements inside a tuple, use std::get:

auto t = std::make_tuple(1,"something");
std::get<0>(t);//will get the first element of the tuple
like image 134
SingerOfTheFall Avatar answered Oct 18 '22 06:10

SingerOfTheFall


You can use std::pair or std::tuple,

std::list<std::pair<int, string>> list;
like image 2
shofee Avatar answered Oct 18 '22 06:10

shofee


You can store the string and the integer in a structure and store the objects of the structure.

Each list element can look like:

struct element  {
    string str;
    int val;
};

This is the C way to handle, please @SingerOfTheFall's answer also.

like image 1
phoxis Avatar answered Oct 18 '22 07:10

phoxis