user3608663
user3608663

Reputation: 125

c++ vector of vector with differents types

How can I declare and push_back a 2D vector of vector with differents types of variables. Is a vector the good way (is it better to use an array)?

my variables are like that :

int id;
string name;
int start;
int end;

and I would like to obtain a list : ((id1 name1 start1 end1), (id2 name2 start2 end2) ...

Sorry for this basic question but I used to work with python, which allow that. Thanks

Upvotes: 2

Views: 164

Answers (2)

vsoftco
vsoftco

Reputation: 56547

You can also use std::tuple (C++11) to push tuples into the vector

#include <iostream>
#include <tuple>
#include <string>
#include <vector>

int main()
{
    using record = std::tuple<int, std::string, int, int>;
    std::vector<record> v;
    v.emplace_back(1, "test1", 2, 3);
    v.emplace_back(10, "test2", 20, 30);

    for(auto&& elem: v) // display the elements
    {
        std::cout << std::get<0>(elem) << " ";
        std::cout << std::get<1>(elem) << " ";
        std::cout << std::get<2>(elem) << " ";
        std::cout << std::get<3>(elem) << std::endl;
    }
}

Upvotes: 2

You don't want a 2D array, you want an array of records. Something like this:

struct Record
{
  int id;
  std::string name;
  int start;
  int end;
};

std::vector<Record> records;

Upvotes: 6

Related Questions