c++ - map 插入导致 VS 2015 中的 C2664 错误,适用于 VS 2013

标签 c++ c2664

这段代码在 VS 2013 中运行完美,但我必须更新到 VS 2015,现在它抛出错误。

我读过 https://msdn.microsoft.com/en-us/library/s5b150wd.aspx并在谷歌上搜索了很多,但我仍然不知道如何解决这个问题。

我正在使用 eigen 数学库来做一些 3d 数学的事情。 Eigen 的 Vector3d 类不能用作容器的键,因此我创建了自己的 Vector3dLite 类来解决这个问题。

class Vector3dLite
{
public:
float VertX, VertY,VertZ;
Vector3dLite(Vector3d& InputVert)
{
    VertX = static_cast<float>(InputVert.x());
    VertY = static_cast<float>(InputVert.y());
    VertZ = static_cast<float>(InputVert.z());
}

Vector3dLite(Vector3dLite& InputVert)
{
    VertX = InputVert.VertX;
    VertY = InputVert.VertY;
    VertZ = InputVert.VertZ;
}
//more operator overloading stuff below
}

这里是编译器抛出错误的地方

map<Vector3dLite, int>  VertexIds;
int unique_vertid = 0;
VertexIds.insert(make_pair(Vector3dLite(tri.Vert1), unique_vertid)); //This line
// Vert1 is an eigen Vector3d object
//...

这是编译器错误:

error C2664: cannot convert argument 1 from 'std::pair<Vector3dLite,int>' to 'std::pair<const _Kty,_Ty> &&'
      with
      [
          _Kty=Vector3dLite,
          _Ty=int,
          _Pr=std::less<Vector3dLite>,
          _Alloc=std::allocator<std::pair<const Vector3dLite,int>>
      ]
      and
      [
          _Kty=Vector3dLite,
          _Ty=int
      ]

我确实尝试在 Vector3dLite 对象之前写 const,但显然语法不正确。

VertexIds.insert(make_pair(const Vector3dLite(tri.Vert1), unique_vertid));

最佳答案

由于映射的值类型将 const 对象作为第一个元素(映射键),您通常不能使用 make_pair 来构造值,因为推断类型不是 const .

您可以创建一个具有显式类型的对:

std::pair<const Vector3dLite, int>(Vector3dLite(tri.Vert1), unique_vertid)

您可以使用 map 的类型

std::map<Vector3dLite, int>::value_type(Vector3dLite(tri.Vert1), unique_vertid)

或者你可以创建一个命名的 const 对象来使用 is make_pair

const Vector3dLite mapkey(tri.Vert1);
make_pair(mapkey, unique_vertid);

另一个注意事项:您的构造函数应该通过 const & 获取它们的参数。

关于c++ - map 插入导致 VS 2015 中的 C2664 错误,适用于 VS 2013,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39396671/

相关文章:

c++ - C++ 中不允许使用静态/全局变量

c++ - 模给出不可能的值

C++ c2664 错误 "cannot convert argument 1 from std::string to _Elem *"

c++ - 将类对象推回到 vector 中

c - 如何解决 Visual Studio 2005 中的错误 C2664 _vswprintf_c_l 错误?

c++ - 编译器会把这个表达式优化成一个临时常量而不是每次迭代都解析它吗?

c++ - 为什么我需要使用 CGAL 和 CMake 构建我的 C++ 程序?

c++ - 拥有大型二维数组 : static int vs int