STL在算法设计中的应用

1.存放主数据(选择容器时不仅要考虑数据的类型,还要考虑数据的处理过程)
eg:字符串可以采用string或者vector来存储,链表可以采用list来存储。
例1.有一段英文由若干单词组成,单词之间用一个空格分隔。编写程序提取其中的所有单词。
解:这里的主数据时一段英文,采用string字符串str存储,最后提取的单词采用vector 容器words存储。对应的完整程序如下:

#include<iostream>
#include<string>
#include<vector>
using namespace std;
void solve(string str,vecttor<string>&words)//产生所有单词
{
string w;
int i=0;
int j=str.find(" ");// 查找第一个空格
while(j!=-1)//找到单词后循环
{
w=str.substr(i,j-i);//提取一个单词
words.push_back(w);//将单词添加到words中
}
}
if(i<str.length()-1)//处理最后一个单词
{
w=str.substr(i);//提取最后一个单词
words.push_back(w);//最后单词添加到words中
}
}
void main()
{
	string str="The following code computes the intersection of two arrays";
	vector<string>words;
	solve(str,words);
	cout<<:所有的单纯词:"<<endl;//输出结果
	vector<string>::iterator it;
	for(it=words.begin;it!=words.end();it++)
	cout<<" "<<*it<<endl;
	}

猜你喜欢

转载自blog.csdn.net/qq_42403069/article/details/86372058
今日推荐