【问题标题】:std::multimap compile errorsstd::multimap 编译错误
【发布时间】:2009-05-28 11:07:27
【问题描述】:

我第一次尝试使用 multimap,但我的应用程序无法编译。 TIA 保罗..

// file dept.h

typedef std::multimap <CString, std::map< CString, CString> > _DeparmentRecord;  // also tryied replacing CString with LPCWSTR

_DeparmentRecord DeparmentRecord;


// file dept.cpp

DWORD CIni::AddNameValue(LPCWSTR Section, LPCWSTR Name, LPCWSTR Value)
{

DeparmentRecord.insert(std::make_pair ( Section, std::make_pair(Name, Value)) );  <-- error here

}

c:\program files\microsoft visual studio 9.0\vc\include\utility(57) : error C2664: 'std::map<_kty>::map(const std::less<_ty> &) ' : 无法将参数 1 从 'const std::pair<_ty1>' 转换为 'const std::less<_ty> &'

1> 与 1> [ 1> _Kty=CString, 1> _Ty=CString 1>] 1> 和 1> [ 1> _Ty1=LPCWSTR, 1> _Ty2=LPCWSTR 1>] 1> 和 1> [ 1> _Ty=CString 1>] 1> 原因:无法从 'const std::pair<_ty1>' 转换为 'const std::less<_ty>' 1> 与 1> [ 1> _Ty1=LPCWSTR, 1> _Ty2=LPCWSTR 1>] 1> 和 1> [ 1> _Ty=CString 1>] 1> 没有可以执行此转换的用户定义转换运算符,或者无法调用该运算符 1> c:\dev\projects\migrator\jobbuilder\jobbuilder\ini.cpp(55) : 参见函数模板实例化 'std::pair<_ty1>::pair>(const std::pair> & )' 正在编译 1> 与 1> [ 1> _Ty1=const CString, 1> _Ty2=std::map 1>]

========== 构建:0 成功,1 失败,0 最新,0 跳过 ==========

【问题讨论】:

    标签: c++ visual-studio-2008 mfc


    【解决方案1】:

    如下改变函数。

    DWORD AddNameValue(LPCWSTR  Section, LPCWSTR  Name, LPCWSTR  Value)
    {
        std::map<CString, CString> aTemp;
        aTemp.insert(std::make_pair (Name, Value));
        DeparmentRecord.insert(std::make_pair (Section, aTemp)) ;
    }
    

    【讨论】:

    • 注意:您将替换 Section 的条目,而不是更新它。
    • 但是 DepartmentRecord 是一个多图。那么不会增加一个新条目吗?
    【解决方案2】:

    您正在尝试将pair&lt; section, pair&lt;...&gt; &gt; 插入到采用pair&lt; section, map&lt;...&gt; &gt; 的地图中。

    【讨论】:

      【解决方案3】:

      std::make_pair(Name, Value) 是一对...但它应该是一个映射。

      STL 错误可能是一个真正的痛苦。使用最新版本的 GCC 会有所帮助,它的错误消息得到了很大改进,但我看到您使用的是 MSVC,所以这对您没有太大帮助。

      【讨论】:

      • 使用最新的 MSVC 也有帮助,你知道的。
      【解决方案4】:

      除了其他答案,std::make_pair 将返回一个 std::pair。不要指望编译器会为您执行从 LPCWSTR 到 CString 的转换。

      【讨论】:

        【解决方案5】:

        除了其他正确答案之外,如果您使用_DeparmentRecordvalue_type typedef 而不是make_pair,您将避免转换问题(并且可能会得到更好的错误消息)。

        DWORD AddNameValue(LPCWSTR Section, LPCWSTR Name, LPCWSTR Value)
        {
          _DeparmentRecord::iterator i =
              DeparmentRecord.insert(_DeparmentRecord::value_type(Section, v)).first;
          i->second[Name] = Value;
        }
        

        还有一点:不要为非本地名称使用前导下划线 - 它们是为标准库保留的。

        【讨论】:

          猜你喜欢
          • 2017-06-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-01
          • 2016-11-13
          • 2021-06-15
          相关资源
          最近更新 更多