Vector that can hold three data types using std::pair

2.7k views Asked by At
vector< pair<pair<int, string> >, string> v;

Also mention how to access them using 'first' and second'. Is it even possible to do this or is "union" or "structure" the only way to create vector that can hold more than two data types?

1

There are 1 answers

2
Jarod42 On BEST ANSWER

std::vector< std::pair<std::pair<int, std::string>, std::string> > v; is possible, with

v[0].first.first = 42;
v[1].first.second = "hello";
v[2].second = "world";

std::tuple is a good alternative:

std::vector<std::tuple<int, std::string, std::string>> v = /*..*/;

std::get<0>(v[0]) = 42;
std::get<1>(v[0]) = "Hello";
std::get<2>(v[0]) = "World";

A proper structure allow to give semantic

struct Person
{
    int age;
    std::string firstName;
    std::string lastName;
};

std::vector<Person> persons = /*...*/;

persons[0].age = 42;
persons[0].firstName = "John";
persons[0].lastName = "Doe";