本文共 2742 字,大约阅读时间需要 9 分钟。
1、问题描述:近来写程序的时候,用到了容器<vector>,所以对这个操作进行了一些了解和操作。
2、<vector>的迭代器的相关函数。
操作 | 效果 |
c.begin() | 返回一个随机存取迭代器,指向第一个元素 |
c.end() | 返回一个随机存取迭代器,指向最后元素的下一个位置 |
c.rbegin() | 返回一个随机存取迭代器,指向逆向迭代的第一元素 |
c.rend() | 返回一个随机存取迭代器,指向逆向迭代的最后元素的下一个位置 |
操作 | 效果 |
c.insert(pos , elem) | 在pos位置上插入一个elem 副本,并返回新元素的位置 |
c.insert(pos , n , elem) | 在pos位置上插入n个elem 副本。无返回值 |
c.insert(pos , beg , end) | 在pos位置上插入区间[beg ; end]内的所有元素的副本,无回传值 |
c.push_back() | 在尾部添加一个elem副本 |
c.pop_back() | 移除最后一个元素(但不回传) |
c.erase(pos) | 移除pos位置上的元素,返回下一元素的位置 |
c.erase(beg , end) | 移除[beg , end]区间内的所有元素,返回下一元素的位置 |
c.resize(num) | 将元素数量改为num(如果size()变大了,多出来的新元素都需要以default构造函数构造完成) |
c.resize(num , elem) | 将元素数量改为num(如果size()变大了,多出来的新元素都需要以elem的副本) |
c.clear() | 移除所有元素,将容器清空 |
4、vector的应用举例
1)删除所有的值为val的元素
vector2)如果只是要删除“与某值相等”的第一个元素,可以这样sentence; sentence.erase( remove(sentence.begin() , sentence.end() ,val) ,sentence.end());
vector3)vector运用实例sentence; std::vector ::iterator pos; pos=find(sentence.begin() , sentence.end() ,val); if( pos != sentence.end() ){ sentence.erase(pos); }
#include "stdafx.h"#include运行结果如图1所示#include #include #include #include //#include #include using namespace std;int main(){ //create empty vector fors trings vector sentence; //reserve memory for five elements to avoid reallocation sentence.reserve(5); //append some elements sentence.push_back("Hello ,"); sentence.push_back("how"); sentence.push_back("are"); sentence.push_back("you"); sentence.push_back("?"); //print elements separated with spaces copy(sentence.begin() , sentence.end() , ostream_iterator (cout," ")); cout << endl; //print "technical data" cout << "max_size():" << sentence.max_size() << endl ; cout << "size():" << sentence.size() << endl ; cout << "capacity():" << sentence.capacity() << endl ; //swap second and fourth element swap(sentence[1] , sentence[3]); //insert element "always" before element "?" sentence.insert(find(sentence.begin() , sentence.end() , "?") ,"always" ); //assign "!" to the last element sentence.back() = "!" ; //print elements separated with spaces copy(sentence.begin() , sentence.end() ,ostream_iterator (cout , " ")); cout << endl ; //print "techinical data " again cout << "max_size():" << sentence.max_size() << endl ; cout << "size():" << sentence.size() << endl ; cout << "capacity():" << sentence.capacity() << endl ; int m; cin>>m;}
5、说明,参考书中,没有添加头文件#include <iterator>。在运行中出错。所以这一点要特别注意一下。
6、致谢王声特同学提供的参考书《C++标准库-自修教程与参考手册》。
7、参考文献
[1] Nicolai M.Josuttis .The C++ Standard Library - A Tutorial and Reference .Pearson Education North Asia Limited,a Pearson Education Company.1998.
(注:翻译:侯捷/孟岩)