您的位置:首页 > 移动开发 > 微信开发

最近刚学到容器Vector,就顺便编写了两个简单的小程序

2015-08-14 14:31 567 查看
个人感觉容器vector就是一个动态数组,因为刚接触有点不习惯,不过写了两个程序后一个是一串数字的首尾相加,另一个是大小写转换,其实感觉真的跟数组很像,下面附上代码和运行结果:
#include"stdafx.h"
#include<iostream>
#include<vector>//其实就相当于一个动态数组
using namespace std;
int main()
{
vector<int>ivec;//定义容器类型和对象名
int ival;
cout<<"请输入数据"<<endl;//把输入的数据读入到vector
while(cin>>ival)
{
ivec.push_back(ival);
}
if(ivec.size()==0)
{
cout<<"vector为空";
return -1;
}
cout<<"vector里面相邻元素之和:"<<endl;
for(vector<int>::size_type ix=0;ix<ivec.size()-1;ix=ix+2)
{
cout<<ivec[ix]+ivec[ix+1]<<"\t";
if((ix+1)%6==0)
cout<<endl;
}
if(ivec.size()%2!=0)
{
cout<<"输入的数是奇数,最后一个没有相邻和:"<<endl;
cout<<"它的值为:"<<ivec[ivec.size()-1];
}
system("pause");
return 0;
}
#include"stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using namespace std;
int main()
{
vector<string>svec;
string str;
cout<<"请输入单词,用空格间隔开,Ctrl+Z结束..."<<endl;
while(cin>>str)
{
svec.push_back(str);
}
if(svec.size()==0)
{
cout<<"vector为空....";
return -1;
}
for(vector<string>::size_type ix=0;ix!=svec.size();++ix)//第一个for循环是对vector中每一个字符串进行判断
{
for(vector<string>::size_type index=0;index!=svec[ix].size();++index)//里面的for循环是vector对每一个个字符串的元素进行判断
{
if(islower(svec[ix][index]))//islower()	如果参数是小写字母,该函数返回true,则满足要求需要转换
{
svec[ix][index]=toupper(svec[ix][index]);//toupper若接收参数是小写字母,则会返回大写字母
}
}
cout<<svec[ix]<<"\t";
if((ix+1)%8==0)
{
cout<<endl;
}

}
system("pause");
return 0;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: