vector的应用举例
来源:互联网 发布:js中tostring方法 编辑:程序博客网 时间:2024/04/30 00:22
1、问题描述:近来写程序的时候,用到了容器<vector>,所以对这个操作进行了一些了解和操作。
2、<vector>的迭代器的相关函数。
4、vector的应用举例
1)删除所有的值为val的元素
vector<string> sentence;sentence.erase( remove(sentence.begin() , sentence.end() ,val) ,sentence.end());2)如果只是要删除“与某值相等”的第一个元素,可以这样
vector<string> sentence;std::vector<string>::iterator pos;pos=find(sentence.begin() , sentence.end() ,val);if( pos != sentence.end() ){sentence.erase(pos);}3)vector运用实例
#include "stdafx.h"#include <iostream>#include <vector>#include <string>#include <algorithm>#include <Windows.h>//#include <iostream>#include <iterator>using namespace std;int main(){//create empty vector fors tringsvector<string> sentence;//reserve memory for five elements to avoid reallocationsentence.reserve(5);//append some elementssentence.push_back("Hello ,");sentence.push_back("how");sentence.push_back("are");sentence.push_back("you");sentence.push_back("?");//print elements separated with spacescopy(sentence.begin() , sentence.end() , ostream_iterator<string>(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 elementswap(sentence[1] , sentence[3]);//insert element "always" before element "?"sentence.insert(find(sentence.begin() , sentence.end() , "?") ,"always" );//assign "!" to the last elementsentence.back() = "!" ;//print elements separated with spacescopy(sentence.begin() , sentence.end() ,ostream_iterator<string>(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;}运行结果如图1所示
图1 3)程序运行结果
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.
(注:翻译:侯捷/孟岩)
0 0
- vector的应用举例
- 定时器的应用举例
- StringBuffer的应用举例
- 栈的应用举例
- 队列的应用举例
- 查表法的应用举例
- 单链表的应用举例
- 栈的应用举例
- 栈的应用举例
- 串的应用举例
- SpringJdbc的应用举例
- 栈的应用举例
- 单链表的应用举例
- 字符串的应用举例
- 栈的应用举例
- Vector,和vector的应用
- WAV文件格式的应用举例
- SQLServer的ISNULL应用举例
- Yii系列——优化程序目录结构
- ShellExecute与ShellExecuteEx的用法
- mysql数据库存储过程游标循环,提前退出
- 人脸识别---Gabor特征(mean pooling和max pooling)
- web前端的vim插件配置
- vector的应用举例
- Week1-3Funny Sentences
- 深入Java集合学习系列:ArrayList的实现原理
- 在网页中使用javascript实现求质数
- 初学C#之list(转载)
- 如何利用qt designer设计的ui文件
- 图片下拉放大
- AngularJS去掉的URL里的#号
- 安卓中使用线条时候遇到的问题