stdcerr
stdcerr

Reputation: 15678

erasing entry from boost vector

First off, I'm relatively new to boost. I have a vector of type: boost::container::vector<std::string> plates and i iterate through it with
for ( unsigned int k = 0; k < plates.size(); k++ ), so far so good.

Now, I need to erase elements from within the loop and I attempted the following: plates.erase(plates.begin()+k); but that gives me the below output and terminates my application:

include/boost/container/vector.hpp:1595: boost::container::vector<T, Allocator, Options>::reference boost::container::vector<T,
, Options>::size_type) [with T = std::__cxx11::basic_string<char>; Allocator = boost::container::new_allocator<std::__cxx11::basic_string<char> >; Options = void; boost
:basic_string<char>&; boost::container::vector<T, Allocator, Options>::size_type = long unsigned int]: Assertion `this->m_holder.m_size > n' failed.

What am I doing wrong here? My loop looks something like this wherefoo() returns a pointer or NULL:

for ( unsigned int k = 0; k < plates.size(); k++ ) {
        if (foo(&lpmap, plates[k]) != NULL){
                std::cout << "DEBUG: erase" << std::endl;
                plates.erase(plates.begin()+k);
        } else {
            std::cout << "print " << plates[k] << std::endl;
        }
    }

EDIT 1

for ( unsigned int k = 0; k < plates.size();) {
        if (foo(&lpmap, plates[k]) != NULL){
                std::cout << "DEBUG: erase" << std::endl;
                plates.erase(plates.begin()+k);
        } else {
            std::cout << "print " << plates[k] << std::endl;
            k++;
        }
    }

Upvotes: 0

Views: 585

Answers (1)

nio
nio

Reputation: 5289

There is an assertion in boost that checks if you try to access an index out of range. so if you used plates[k] with k more than actual size, you get an assertion.

You can see the check right in the boost code: https://www.boost.org/doc/libs/master/boost/container/vector.hpp.

Upvotes: 1

Related Questions