ashaw
ashaw

Reputation: 187

Random access iterators - does vector.end() - vector.begin() = vector.size() in C++;

I would like to write something analogous to the following code

class c{
  public:
    //...
    big_structure* find(int e){
        auto it = std::lower_bound(v1.begin(), v1.end(), e);
        return v2[it - v1.begin()];
    }
  private:
    std::vector<int> v1;            //v1 is sorted;
    std::vector<big_structure*> v2; //v2.size() = v1.size() + 1
}

Is this legal, moreover will it return v2[v1.size()] when e is not in v1?

If possible I would like to not special case it == v1.end().

Upvotes: 0

Views: 836

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254621

Is this legal, moreover will it return v2[v1.size()] when e is not in v1?

Yes. Past-the-end random-access iterators can be used in arithmetic with other iterators from the same sequence, giving the expected result.

Upvotes: 6

Related Questions