c++ - 数组和vector的用法
怪我咯
怪我咯 2017-04-17 13:05:16
0
2
695
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
阿神

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);

左手右手慢动作

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template