1

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.

1
  • Your value type is not a pointer, hence new vector<string> is redundant, the operation Subjects[s] will already construct the vector correctly - if it did not exist at key s. Commented Mar 10, 2014 at 8:55

1 Answer 1

4

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, and if I want to print this value from map? what should I do?
You need to iterator through the map then iterator through iterator through vector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.