gpt4 book ai didi

c++ - 为什么我可以在 map 中使用 push_back 但不能在 set 中使用 back_inserter?

转载 作者:行者123 更新时间:2023-11-30 01:12:12 24 4
gpt4 key购买 nike

C++ Primer 5th的第11章(关于关联容器)说:

The associative containers do not support the sequential-container position-specific operations, such as push_front or back. Because the elements are stored based on their keys, these operations would be meaningless for the associative containers.

可是,我练了两个功法之后,我就糊涂了:

  1. 给定一个 map<string, vector<string>> , 要求添加一个 vector<int>给定 key ,我的(工作)解决方案是:

    using Map = map<string, vector<string>>;
    Map my_map;
    for(string ln; cin >> ln)
    for(string cn; cin >> cn)
    my_map[ln].push_back(cn);
  2. 但是在第二个练习中,假设 c 是一个字符串的多重集,v 是一个字符串 vector ,是 copy(v.begin(), v.end(), back_inserter(c));合法还是非法?

当我使用它时,我得到了这个错误:

error: 'class std::multiset >' has no member named 'push_back'`

我所知道的是back_inserter不起作用,因为没有 push_back .

最佳答案

my_map[ln].push_back(cn)不打电话 push_backmap 上( my_map ),它调用 push_backmap 上s mapped_type这是vector<string> - 您可以使用 operator[] 访问它(my_map[ln])。

您的声明my_map[ln].push_back(cn)本质上等同于:

vector<string>& v = my_map[ln];
v.push_back(cn);

关于c++ - 为什么我可以在 map 中使用 push_back 但不能在 set 中使用 back_inserter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34610559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com