Sharu Gupta
Sharu Gupta

Reputation: 201

how to clear a boost::iterator_range

I have pointer p to a boost::iterator range pointing to a vector. I cleared the underlying vector. Since the underlying vector is cleared, the iterator pair of the boost::iterator range is invalidated. There is no clear function for a boost::iterator_range.

How can I clear the boost::iterator range?

p->begin() = p->end()

does not result in p.empty() returning true

Upvotes: 1

Views: 641

Answers (1)

sehe
sehe

Reputation: 393114

Using a range [end(), end()) does in fact make empty() return true. However, you can also just assign a default constructed iterator range:

*p = {};

Here's a live demonstration of various approaches:

Live On Coliru

#include <boost/range/iterator_range.hpp>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> is { 1,2,3 };
    auto range = boost::make_iterator_range(is.begin(), is.end());
    std::cout << "range empty? " << std::boolalpha << range.empty() << "\n";

    range = boost::make_iterator_range(is.end(), is.end());
    std::cout << "range empty? " << std::boolalpha << range.empty() << "\n";

    is.clear();

    range = {};
    std::cout << "range empty? " << std::boolalpha << range.empty() << "\n";
}

Prints

range empty? false
range empty? true
range empty? true

Upvotes: 1

Related Questions