Home  >  Q&A  >  body text

c++ - 数组和vector的用法

怪我咯怪我咯2715 days ago660

reply all(2)I'll reply

  • 阿神

    阿神2017-04-17 13:07:16

    You can write: vec.begin() + i; or vec[i]
    In addition, when using vector, it is better to pass "reference".
    void func(vector<int>& vec);

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:07:16

    STL uses iterator to abstract. In your case, regardless of whether func is read-only, you can refer to the writing method of std::sort.

    In general, that’s it,

    void func(int* array, int size);
    

    changed to

    template<TIterator>
    void func(TIterator begin, TIterator end);
    

    As a simple example, binary search method:

    template<typename TIterator> // 需要random iterator,如果使用了C++ concept的话可以有效美化错误信息
    bool find(TIterator begin, TIterator end, std::remove_reference_t<decltype(**(TIterator*)nullptr)> value)
    {
        auto size = end - begin;
        if (size <= 0) return false;
        auto position = begin + (size / 2);
        auto middle = *position;
        if (middle > value) return findx(begin, position, value);
        if (middle < value) return findx(position+1, end, value);
        return true;
    }
    
    vector<int> x = {1, 2, 3, 4, 5};
    find(x.begin(), x.end(), 2); // true
    find(x.begin() + 2, x.begin() + 3, 2); // false
    

    It can be seen that iterator was invented to simulate the concept of pointer. However, pointer arithmetic requires that the content is stored continuously, while iterator does not. So for the convenience of thinking, you only need to think of iterator as a pointer.

    reply
    0
  • Cancelreply