c++ - std::pair of std::string 和自定义类无法在 std::map::insert(std::make_pair(string, class)) 上复制

标签 c++ insert std-pair

这个错误:

error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::string' (or there is no acceptable conversion)  c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility  216

出现在这个函数的唯一行:

void Animation::AddAnimation(std::string name, AnimationFrameSet& animation) {
    _animations.insert(std::make_pair(name, animation));
}

_animationsstd::map<std::string, AnimationFrameSet>

AnimationFrameSet 声明了一个 operator=(...) 和一个复制构造函数,但奇怪的是,编译器说它在尝试复制 const std::string 时失败了。 ...即使字符串甚至没有作为 const 传入.

我这辈子都想不通(甚至想不起来!:P)为什么这是/应该抛出/抛出错误。

谢谢。

编辑

我有点困惑为什么这不起作用是因为不同的类使用非常相似的实现并且它不会抛出错误:

BITMAP* BitmapCache::GetBitmap(std::string filename) {
    //Return NULL if a bad filename was passed.
    if(filename.empty()) return NULL;
    if(exists(filename.c_str()) == false) return NULL;

    //Reduce incorrect results by forcing slash equality.
    filename = fix_filename_slashes(&filename[0]);

    //Clean the cache if it's dirty.
    CleanCache();

    //Search for requested BITMAP.
    MapStrBmpIter _iter = _cache.find(filename);

    //If found, return it.
    if(_iter != _cache.end()) return _iter->second;

    //Otherwise, create it, store it, then return it.
    BITMAP* result = load_bmp(filename.c_str(), NULL);
    if(result == NULL) return NULL;
    /*Similar insert line, a non-const std::string that was passed in is passed to a std::make_pair(...) function*/
    _cache.insert(std::make_pair(filename, result));
    return result;
}

类型定义:

typedef std::map<std::string, BITMAP*> MapStrBmp;
typedef MapStrBmp::iterator MapStrBmpIter;

最佳答案

失败的原因是因为您正在使用的 std::map 容器需要一个常量值作为键值。

查看 std::map 的文档 here .

例子:

class TestClass
{
};

std::map< const std::string, TestClass > myMap;
std::pair< const std::string, TestClass > firstElement = std::make_pair("test", TestClass() );
myMap.insert( firstElement );

关于c++ - std::pair of std::string 和自定义类无法在 std::map::insert(std::make_pair(string, class)) 上复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7776105/

相关文章:

c++ - 将打印机设备上下文另存为图像

c++ - 如何将自定义对象插入到 std::map 中?

c++ - 更正友元定义以授予 std::map 对私有(private)默认构造函数的访问权限

c++ - 输出没有临时的返回对

c - 在标准 C 中使用 pair 和 make_pair

c++ - 绑定(bind)套接字失败,errno 88

c++ - 从Release版本中省略字符串常量的最佳方法

c++ - OpenCV:如何将图像保存在一个大矩阵中然后分别调用它们?

php - PDO 插入不工作

c - 二叉树插入和删除 - C