anthony
anthony

Reputation: 902

Error: No Match for operator[]

I'm working on an openFrameworks project, and I'm using a vector to store 3d mesh index locations. However, when attempting to access the data, I'm getting:

error: no match for 'operator []' in ((icoSphere*)this)->icoSphere::subIndicies[i]

The data type is ofIndexType.

Here are some snippets

icoSphere.h file:

// vector created        
std::vector<ofIndexType> subIndicies;

icoSphere.cpp file:

// 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
}

Both the vector and the iterator are ofIndexType (an openFrameworks data type, which is essentially an unsigned integer). Can't sort out why it's saying [] isn't an operator.

Upvotes: 3

Views: 2526

Answers (2)

Mr.C64
Mr.C64

Reputation: 42944

std::vector::operator[]() expects an integer index (a size_t) referring to a vector item:

0 --> 1st item
1 --> 2nd item
2 --> 3rd item
....

But in your code you passed an iterator (which is not an integer index) as parameter to std::vector::operator[](), which is invalid:

// *** '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
}

Either use iterators to access vector items, or use integer indices.
In C++11+, it's also possible to use range-based for loops.

// 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);
}

PS
Note that, when you increment an iterator, it's better to use pre-increment ++it instead of post-increment it++ (it++ is a "premature pessimization").

Upvotes: 7

jsantander
jsantander

Reputation: 5102

i is an iterator, just do

subMesh.addIndex(*i); 

Upvotes: 5

Related Questions