c++ - 在 map 中使用字符串 vector

标签 c++ string vector dictionary

我有一个带有字符串键的映射,第二个属性应该是 vector 。

声明:

map <string, vector<string> > Subjects;

然后当我想用它来增加值(value)时。

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

s 和 n 是字符串。我只在第一行出错。它说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> >*’) .我试图将 vector 指针提供给 map ,但没有帮助。

最佳答案

Subjects 类型的值不是指针,您不能为其分配 new

如果n是字符串类型,就调用:

map <string, vector<string> > Subjects;

std::string n("hello");

Subjects[s].push_back(n);

编辑:

要从 map 中打印此值,您需要在 map 中找到元素,然后迭代 vector 。

auto it = Subjects.find(s);

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

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

关于c++ - 在 map 中使用字符串 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22295674/

相关文章:

c++ - 链接 OpenCV 时 undefined symbol

java - 在java中复制字符串中的前N个单词

python - boost python raw_function 方法

c - 我想将字符串从文件复制到变量二维字符中

c - strncat 添加了一些意外的字符

arrays - 如何交换数组、切片或 Vec 的元素?

c++ - C++ Eclipse (Linux-Mint12) 中的转换问题

c++ - 为什么样本不是随机填充我的 vector ?

c++ - 在指针场景中使用 std::shared_ptr

C++ 链表行为