简体   繁体   中英

error: vector iterators incompatible

This is the line which causes the error

vector<transform>::iterator transformIter;
    for (transformIter = (*objIter)->transforms.begin(); transformIter != (*objIter)->transforms.end(); objIter++) {
                    handleTransform((*transformIter));
                }

It occurs on the second iteration of the loop regardless of how many transofrms are in the vector.

The obj struct looks like this:

struct obj {

    vector<glm::vec4> vertices;
    vector<int> elements;
    vector<object> objects;
    vector<transform> transforms;


};

and the function handleTransform is:

void handleTransform(transform currentTransform) {

    if (currentTransform.type == 'r') {
        glRotatef(currentTransform.coordinates.x, 1.0f, 0.0f, 0.0f);
        glRotatef(currentTransform.coordinates.y, 0.0f, 1.0f, 0.0f);
        glRotatef(currentTransform.coordinates.z, 0.0f, 0.0f, 1.0f);
    }

    if (currentTransform.type == 's') {
        glScalef(currentTransform.coordinates.x, currentTransform.coordinates.y, currentTransform.coordinates.z);
    }

    if (currentTransform.type == 't') {
        glTranslatef(currentTransform.coordinates.x, currentTransform.coordinates.y, currentTransform.coordinates.z);
    }

}

Iterating through the other vectors in an obj doesn't cause any vector issues, so I have to imagine it's something to do with the handleTransform function, but I can't figure it out.

You are erroneously incrementing objIter , not transformIter :

for (transformIter = (*objIter)->transforms.begin(); 
     transformIter != (*objIter)->transforms.end(); 
     objIter++) // ??

It should be:

for (transformIter = (*objIter)->transforms.begin(); 
     transformIter != (*objIter)->transforms.end(); 
     ++transformIter) 

To avoid mistakes like this, use std::for_each , or if using C++ 11, a ranged-based for loop:

http://en.cppreference.com/w/cpp/language/range-for

With either of these options, you eliminate the need to declare iterators, make mistakes iterating to the next item, or if not those issues, perform a post-increment instead of a faster pre-increment of the iterator (as your original code is doing).

++transformIter替换objIter++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM