【问题标题】:C++ compilation issue when trying to insert into a map尝试插入地图时出现 C++ 编译问题
【发布时间】:2013-06-28 09:37:01
【问题描述】:

我得到的 C++ 编译器错误是:

line 27: Error: Could not find a match for 
     std::multimap<std::string, std::vector<std::string>, 
                   std::less<std::string>, 
                   std::allocator<std::pair<const std::string, 
                       std::vector<std::string>>>>
     ::insert(std::pair<std::string, std::vector<std::string>>) 
     needed in main().
1 Error(s) detected.

下面是我的程序:

#include<iostream>
#include<sstream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;

typedef multimap<string, vector<string> > mos_map;
typedef multimap<string, vector<string> >::iterator mos_map_it;

int main()
{

    mos_map mos;
    mos_map_it it;

    vector<string> v1;

    v1.push_back("a");
    v1.push_back("b");
    v1.push_back("c");
    v1.push_back("mo1");

    std::string a(*(v1.end()-1));

    mos.insert(std::pair< std::string, vector< std::string > >(a,v1));
    //Is the above not the right way to to insert an element into the map?
    return 0;
}

当我尝试以字符串为键插入向量作为值时,上面的代码引发编译错误。我正在使用 solaris。

【问题讨论】:

  • 你忘了#include &lt;string&gt;
  • 你使用的编译器是什么?
  • 使用make_pair(a, v1)
  • 在 gcc 4.8.1 上编译得很好,猜想它在引擎盖下的某处包含
  • @caribou,即使你的建议也没有用。这是solaris编译器的问题吗?我使用的编译器是 /opt/SUNWspro/bin/CC

标签: c++ map vector


【解决方案1】:

在地图中插入元素的正确方法是:

mos[a] = v1

(由于 map 重载了 operator[])

【讨论】:

  • 这是方便的方法。这也是一种效率较低的方法:如果映射中尚未出现a,则首先创建一个默认值,然后将v1 分配给新的映射条目。 insert 不是这种情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 2021-10-17
  • 2016-02-20
  • 2011-07-18
  • 1970-01-01
相关资源
最近更新 更多