-1
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?

theavatar
  • 115
  • 1
  • 9

1 Answers1

4

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";
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • std::get<0>(v[0]) = 42; std::get<1>(v[0]) = "Hello"; std::get<2>(v[0]) = "World"; But Iam not able to assign values got from the input int n; cin>>n; get<0>(v[0])=n; Gives seg fault. – theavatar Jan 07 '17 at 05:22
  • Thanks. You convinced me that going to a POD struct is better than messing around with tuples.... at least for my application. – rayryeng Jun 07 '18 at 19:09