简体   繁体   中英

Iterating over an std::vector when vector size changes. (C++)

I wrote a very simple code that iterates over a vector. The problem is that this vector changes its size on each iterator.

The vector is a private variable of a class. And the code goes like this:

std::vector<boost::filesystem::path> headerVector;

The loop is a for loop inside a member function of the same class.

It seems that the for loop reads the vector size once and then iterates until that number is reached, but the vector increases it's size on some iterations (not infinite).

How can I make it iterate until the value of IT and the CURRENT size of the vector are equal?

The code goes like this:

void HeaderObtainer::mapIterator( boost::filesystem::path aPath )
{
    bool exist;
    std::vector<boost::filesystem::path>::iterator it; //iterator for boost path.

    for (it = headerVector.begin(); it!= headerVector.end(); it++) // For each?
        {
            aPath = *it;
            exist = HeaderSources::fileExists( aPath ); //Returns bool.
            fileSearch ( exist, aPath );
        }
}

Thank you!

Assuming that fileSearch may add element at the end of headerVector , but cannot remove element. Following may help:

void HeaderObtainer::mapIterator(boost::filesystem::path aPath)
{
    for (std::size_t i = 0; i != headerVector.size(); ++i) {
        aPath = headerVector[i];
        bool exist = HeaderSources::fileExists(aPath); //Returns bool.
        fileSearch(exist, aPath);
    }
}

Note that std::vector iterators might be invalidated , if its size changes. So, if the loop changes vector size, your code causes undefined behavior.

If another thread changes the vector, there's undefined behavior as well, because std::vector is not thread-safe, so you should protect the critical section (eg. using mutex).

You maybe might use a while instead of for and dynamically manage the iterator. I think that with a copy of the iterator from the last iteration you can return to the last position after removing something. Or, if the vector is going to be small, just restart the loop when the size of the vector changes with it=headerVector.begin();

(Actually I'm not sure if this last one would work because the vector size has changed, but I'm sure you could do this with a while)

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