分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow
1 对于Vector,迭代器跟索引差别不大
for ( int i=0; i < vecVector.size(); i++ ){..}
- 1
- 2
- 3
- 4
- 5
for (auto iter = vecVector.begin(); iter != vecVector.end(); iter++){ ...}
- 1
- 2
- 3
但是,仅仅可以对支持 operator[](std::size_t)
的容器使用索引
2 但是在vector中删除、插入元素,迭代器比索引更加方便
some_iterator = some_vector.begin();while (some_iterator != some_vector.end()){ if (/* some condition */) { some_iterator = some_vector.erase(some_iterator); // some_iterator now positioned at the element after the deleted element } else { if (/* some other condition */) { some_iterator = some_vector.insert(some_iterator, some_new_value); // some_iterator now positioned at new element } ++some_iterator; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
3 迭代器让你的代码更加通用
比如:
typedef std::vector<int> Container ;void doSomething(Container & p_aC){ for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it) { int & i = *it ; // i is now a reference to the value iterated // do something with "i" }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
如果,使用list替代上面的vector,那么迭代器的优势就显现出来了。
4 更重要的是,迭代器用于算法
copy(v.begin(), v.end(), l.begin());for (auto it = v.begin(); it != v.end(); ++it) { // if the current index is needed: auto i = std::distance(v.begin(), it); // access element as *it // any code including continue, break, return}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
5 迭代器更具有oop思想
6 模板编程
template <class Container>double product( const Container & container ){ Container::iterator i = container.begin(); double prod = 1; while ( i != container.end() ) prod *= *i++; return prod;}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Iterators make your code more generic.
for_each + lambda
std::for_each(v.begin(), v.end(), [](T const& elem) { // if the current index is needed: auto i = &elem - &v[0]; // cannot continue, break or return out of the loop});
- 1
- 2
- 3
- 4
- 5
- 6
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow