我用iterator犯的一个错误

来源:互联网 发布:怎样在淘宝网买东西 编辑:程序博客网 时间:2024/04/19 13:43

 

昨天去一家公司上机测试,以前老是看一些STL的书籍,没有直接用来做过任何东西。所以一下子出丑了。

 

这样一个问题:

 

#include <vector>

#include <iostream>

void printArr(const std::<int>& a)

{

       for(std::vector<int>::iterator it = a.begin(); it != a.end(); it++)

              std::cout << a[it] << std::endl;

}

 

这段程序死活编译不过去,无奈有时间限制,我就改成了以下方法

#include <vector>

#include <iostream>

void printArr(const std::<int>& a)

{

       for(int i = 0; i < a.size(); i++)

              std::cout << a[i] << std::endl;

}

编译通过。但是实在是心里不爽,毕竟自己对这个东西没有很好的理解和使用。、

第一段代码犯了两个错误:

第一:作为const类型的参数a,要想遍历a需要适用const_iterator

第二:做为iterator,要访问它的数值用法是*it,而不是a[it]

所以正确的方法是:

#include <vector>

#include <iostream>

void printArr(const std::<int>& a)

{

       for(std::vector<int>::const_iterator it = a.begin(); it != a.end(); it++)

              std::cout << *it << std::endl;

}

 

原创粉丝点击