无法从向量<T>转换为 T

Cannot cast from vector<T> to T

本文关键字:转换 gt lt 向量      更新时间:2023-10-16

我有一个函数,它接受一些T类型的参数:

constexpr inline const bool isReflex(const T x1, const T y1, const T x2, const T y2, const T x, const T y)

使用项目调用此函数形成一个向量 yiels 到错误C2664: Cannot convert argument 1 from 'vector<T, std::allocator<_Ty>>' to 'const T'

vector<T>* v = new vector<T>; // I am not creating the vector myself, this is just for demonstration.
// The real vector is passed as const vector<T>* to a function executing the following:
if (isReflex(v[i-2], v[i-1], v[i], v[i+1], v[i+2], v[i+3]))
//           ^^^^^^ error

这对我来说毫无意义,因为我传递的不是矢量,而是它的内容。是什么原因导致这种行为?

编辑

哎哟。

这是因为v不是向量,而是指向向量的指针。因此,您需要一个取消引用运算符:

if (isReflex((*v)[i-2], (*v)[i-1], (*v)[i], (*v)[i+1], (*v)[i+2], (*v)[i+3]))

错误消息可能看起来不完全清楚的原因是[]运算符也适用于指针,并且行为类似于具有偏移量的取消引用运算符。换句话说,C++编译器将变量v视为内置的向量数组,将索引[i-2]应用于该数组,并报告错误,因为v[i-2]表达式的类型是向量。

实向量作为const vector<T>*传递给函数

您可以创建一个引用变量来保留旧语法:

const vector<T> *pv // function parameter
const vector<T>& v = *pv;
// This will work now
if (isReflex(v[i-2], v[i-1], v[i], v[i+1], v[i+2], v[i+3])) {
...
}

您在type *对象上使用[n]运算符 - 在您的情况下vector<T> *.您的编译器可能会将其解释为"给我从此地址开始计数的第 n 个向量",而不是"给我此地址指向的向量中的第 n 个元素"。