vector:
仅能对确知已存在的元素进行下标操作,但下标操作也不能添加元素,必须用push_back()才可
1).vector的输入和输出:(size_type类型)
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
//read words from the standard input and store then as elements in a vector
string word;
vector<string> text; //empty vector
while(cin>>word)
{
text.push_back(word);
}
//output
for(vector<string>::size_type ix=0;ix!=text.size();++ix)
{
cout<<text[ix]<<endl;
}
return 0;
}
2).读一组整数到vector对象,计算并输出每对相邻元素的和,如果读入元素个数为奇数。提示用户最后一个元素没有求和,并输出其值
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> ivec;
int val;
//read input
cout<<"Enter numbers((Ctrl+z) to end: )"<<endl;
while(cin>>val)
ivec.push_back(val);
//calculating
if(ivec.size()==0)
{
cout<<"No elements?!"<<endl;
return -1;
}
cout<<"Sum of each pair of adjacent elements in the vector: "
<<endl;
for(vector<int>::size_type ix=0;ix!=ivec.size();ix=ix+2)
{
cout<<ivec[ix]+ivec[ix+1]<<"/t";
if((ix+1)%6==0)
cout<<endl;
}
if((ivec.size()%2)!=0)
cout<<endl
<<"The last element is not been summed"
<<"and its value is"
<<ivec[ivec.size()-1]<<endl;
return 0;
}
3).读一组整数到vector对象,计算并输出首尾配对元素的和,若居中元素没有计算给出提示
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
//读入数据到vector对象
cout<<"Please Enter some integrated numbers: "<<endl;
while(cin>>ival)
ivec.push_back(ival);
//计算首尾配对元素的和并输出
if(ivec.size==0)
{
cout<<"No elements in the vector"<<endl;
return -1;
}
cout<<"Sum of each pair of counterpart elements in the vector: "<<endl;
vector<int>::size_type cnt=0;
for(vector<int>::size_type first=0,last=ivec.size()-1;first<last;++first,--last)
{
cout<<ivec[first]+ivec[last]<<"/t";
++cnt;
if(cnt%6==0) //每行输出6个元素
cout<<endl;
}
if(first==last) //提示居中元素没有求和
cout<<endl
<<"The center element is not been summed"
<<"and its value is"
<<ivec[first]<<endl;
return 0;
}
3).读入一段文本到vector对象,每个单词存储为一个vector中的一个元素,把vector对象中每个单词转化为大写字母,输出vector对象转换后的元素,每八个单词作为一行输出
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
int main()
{
vector<string> svec;
string str;
//读入文本到vector对象
cout<<"Enter text(Ctrl+Z tp end): "<<endl;
while(cin>>str)
svec.push_back(str);
//将vector对象中每个单词转化为大写字母,并输出
if(svec.size()==0)
{
cout<<"No string?!"<<endl;
return -1;
}
cout<<"Transformed elements from vectors: "
<<endl;
for(vector<string>::size_type ix=0;ix!=svec.size();++ix)
{
for(vector<string>::size_type index=0;index!=svec[ix].size();++index)
{
if(islower(svec[ix][index]))
//单词中下标为index的字符为小写字母
svec[ix][index]=toupper(svec[ix][index]);
cout<<svec[ix][index]<<" ";
if((ix+1)%8==0) //每8个单词为一行输出
cout<<endl;
}
}
return 0;
}