随机访问迭代器 - 在C ++中的vector.end() - vector.begin()= vector.size();

时间:2013-10-21 17:00:16

标签: c++ vector iterator

我想写一些类似于以下代码的东西

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
}

这是否合法,而且当e不在v1中时它会返回v2 [v1.size()]吗?

如果可能的话我不想特殊情况== v1.end()。

1 个答案:

答案 0 :(得分:6)

  

这是否合法,而且当v2[v1.size()]不在e时会返回v1吗?

是。过去的随机访问迭代器可以用于与来自相同序列的其他迭代器的算术运算,从而得到预期的结果。