错误:运算符[]无匹配

ant*_*ony 3 c++ vector openframeworks

我正在开发一个openFrameworks项目,我正在使用它vector来存储3d网格索引位置.但是,在尝试访问数据时,我得到:

error: no match for 'operator []' in ((icoSphere*)this)->icoSphere::subIndicies[i]
Run Code Online (Sandbox Code Playgroud)

数据类型是ofIndexType.

这是一些片段

icoSphere.h文件:

// vector created        
std::vector<ofIndexType> subIndicies;
Run Code Online (Sandbox Code Playgroud)

icoSphere.cpp文件:

// items added to vector
ofIndexType indA = mesh.getIndex(0);
ofIndexType indB = mesh.getIndex(1);
ofIndexType indC = mesh.getIndex(2);

subIndicies.push_back(indA);
subIndicies.push_back(indB);
subIndicies.push_back(indC);

// iterate through vector
for (std::vector<ofIndexType>::iterator i = subIndicies.begin(); i !=subIndicies.end(); i++)
{
    subMesh.addIndex(subIndicies[i]); // here is where the error occurs
}
Run Code Online (Sandbox Code Playgroud)

向量和迭代器都是ofIndexType(openFrameworks数据类型,本质上是无符号整数).无法理清为什么它说[]不是运营商.

Mr.*_*C64 7

std::vector::operator[]()期望一个整数索引(a size_t)引用一个向量项:

0 --> 1st item
1 --> 2nd item
2 --> 3rd item
....
Run Code Online (Sandbox Code Playgroud)

但是在你的代码中你传递了一个迭代器(它不是一个整数索引)作为参数std::vector::operator[](),这是无效的:

// *** 'i' is an iterator, not an integer index here ***
//
for (vector<ofIndexType>::iterator i = subIndices.begin(); i != subIndices.end(); i++)
{
    subMesh.addIndex(subIndices[i]); // here is where the error occurs
}
Run Code Online (Sandbox Code Playgroud)

使用迭代器访问矢量项,或使用整数索引.
在C++ 11 +中,也可以使用基于范围的for循环.

// Integer index
for (size_t i = 0; i < subIndices.size(); ++i)
{
    subMesh.addIndex(subIndices[i]);
}

// Iterator
for (auto it = subIndices.begin(); it != subIndices.end(); ++it)
{
    subMesh.addIndex(*it);
}

// Modern C++11+ range for
for (const auto & elem : subIndices)
{
    subMesh.addIndex(elem);
}
Run Code Online (Sandbox Code Playgroud)

PS
注意,当你增加迭代器时,最好使用预增量++it而不是后增量it++(it++是"过早的悲观化").


jsa*_*der 5

我是一个迭代器,就是这样

subMesh.addIndex(*i); 
Run Code Online (Sandbox Code Playgroud)