C/C++ STL

来源:互联网 发布:音箱设计软件 编辑:程序博客网 时间:2024/06/05 00:30

之前对C++ STL一点不懂。在看list时,看到list中insert方法返回值为迭代器。

在看迭代器中,了解到迭代器可被用来访问一个容器类的所包函的全部元素。
</pre><pre class="cpp" name="code">如下代码对vector容器对象生成和使用了迭代器:
#include<iostream>#include<vector>using namespace std;vector<int> the_vector;vector<int>::iterator the_iterator;int main(){for(int i=0;i<10;i++)the_vector.push_back(i);//push_back()添加值为i的元素到当前vector末尾int total=0;the_iterator=the_vector.begin();//begin()函数返回一个指向当前vector起始元素的<a target=_blank href="mk:@MSITStore:D:\用户目录\Documents\Tencent%20Files\1508108373\FileRecv\C语言程序设计\C语言库函数参考.chm::/cppreference.com/iterators.html">迭代器</a>.
while(the_iterator!=the_vector.end()){   //end() 函数返回一个指向当前vector末尾元素的<strong>下一位置</strong>的<a target=_blank href="mk:@MSITStore:D:\用户目录\Documents\Tencent%20Files\1508108373\FileRecv\C语言程序设计\C语言库函数参考.chm::/cppreference.com/iterators.html">迭代器</a>.total+=*the_iterator;the_iterator++;//++操作符用来递增迭代器,以访问容器中的下个对象。}cout<<"Total="<<total<<endl;return 0;}

算不上完全自己做的。但是也是个进步吧。
参考:<a target=_blank href="http://blog.chinaunix.net/uid-20773165-id-1847758.html">http://blog.chinaunix.net/uid-20773165-id-1847758.html</a>


0 0