c++ - pointIndex无法从c++中的 vector 中检索项目

标签 c++ visual-studio-2010 vector

在 Visual Studio '12 中出现以下编译错误

error C3867: 'std::vector<_Ty>::at': function call missing argument list; use '&std::vector<_Ty>::at' to create a pointer to member line 39

代码

Vector2dVector mVertices;

/// other code

for (int pointIndex = 0; pointIndex < points.size(); pointIndex++) {
    mVertices.push_back(Vector2d(pointIndex * 2.0f, pointIndex * 3.0f ));
}

int size = mVertices.size();
CCPoint *pointArr = new CCPoint[size];
for(int i = 0; i < size; i++) {
    Vector2d vec2 = mVertices.at[i];  //Line 39 
    //pointArr[i].x = vec2->GetX();
    //pointArr[i].y = vec2->GetY();
}

最佳答案

问题是你这里有一个错字:

Vector2d vec2 = mVertices.at[i];  //Line 39 
                            ^ ^

您应该将 ()std::vector::at 方法调用一起使用,而不是 []:

Vector2d vec2 = mVertices.at(i);  //Line 39 

另一种方法是使用 std::vector::operator[] 重载(而不是 at()):

Vector2d vec2 = mVertices[i];

区别在于std::vector::at()对 vector 索引进行边界检查,并抛出异常std::out_of_range 如果索引超出范围(防止缓冲区溢出)。

相反,如果您使用 std::vector::operator[],边界检查将被禁用。

换句话说,使用 std::vector::operator[] 你有更快的代码,但你没有对 vector 索引的运行时检查(所以你必须注意你的索引,以避免危险的缓冲区溢出)。

(更准确地说,在 Visual Studio 中,如果 _SECURE_SCL 设置为 1,则 std::vector::operator[] 也有边界检查>).

关于c++ - pointIndex无法从c++中的 vector 中检索项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15945236/

相关文章:

c++ - 使用 for 循环删除 vector 中的元素

c++ - 使用 gsl 库并行化线性代数

asp.net - 将 WCF 库项目转换为 WCF Web 服务(WCF 应用程序)项目类型

C++ AMP 迭代具有不同维度的 array_views

c++ - 带有 set 的 std::inserter - 插入到 begin() 或 end()?

C++ 可变参数——我使用它们的方式好还是不好?有好的选择吗?

visual-studio-2010 - 找不到多文件程序集 'normnfc.nlp' 的文件 'mscorlib.dll'

c++如何在内部循环中使用带自动的 vector 删除对象

python - 用 scipy odeint 在 python 中求解向量常微分方程

c++ - 如何迭代无序映射的特定键的值?