Grim
Grim

Reputation: 37

Using string vector in map

I have a map with string key and the second atribute should be vector.

Declaration:

map <string, vector<string> > Subjects;

and then when I want to use it for adding values.

Subjects[s] = new vector<string>;
Subjects[s].push_back(n);

s and n are strings. I got error just for the first line. It says error: no match for ‘operator=’ (operand types are ‘std::map<std::basic_string<char>, std::vector<std::basic_string<char> > >::mapped_type {aka std::vector<std::basic_string<char> >}’ and ‘std::vector<std::basic_string<char> >*’) . I tried to give pointer of vector to map, but it doesn't help.

Upvotes: 1

Views: 5480

Answers (1)

billz
billz

Reputation: 45470

value of Subjects type is not a pointer, you can't allocate new to it.

if n is string type, just call:

map <string, vector<string> > Subjects;

std::string n("hello");

Subjects[s].push_back(n);

Edit:

To print this value from map, you need to find the element in map then iterator the vector.

auto it = Subjects.find(s);

if (it != Subjects.end())
{
    auto& vIt = it->second;

    for (auto elem : vIt)
    {
        cout << elem << endl;
    }
}

Upvotes: 4

Related Questions