user3806521
user3806521

Reputation: 53

A string vector inside an int vector?

I'm aware of multidimensional vectors for example vector<vector<int>> but I was wondering if you can have a vector of a type inside a vector of another type.

An example would be a string vector inside an integer vector, so I would access it like this:

vectorName[0]["A"];

Can this be done?

Thanks.

Upvotes: 0

Views: 98

Answers (2)

Felix Glas
Felix Glas

Reputation: 15524

std::vector is a random access data structure by design, and is supposed to store a contiguous data array where the elements are accessible via an integral index number.

You can not use std::vector in the way you describe, it seems more like a string->value_type mapping, e.g. std::map<std::string, T>.

You could use a std::vector of std::maps to get the behaviour you want.

std::vector<std::map<std::string, int>> vec{
    {{"a1", 1}, {"a2", 2}},
    {{"b1", 1}, {"b2", 2}}
};

std::cout << vec[0]["a2"] << std::endl; // 2

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

This expression is more appropriate for declaration

std::vector<std::map<std::string, T>> vectorName;

In this case you will be able to write for example

T value = vectorName[0]["A"];

where T is some type.

Upvotes: 3

Related Questions