|
楼主 |
发表于 2017-12-21 23:06:16
|
显示全部楼层
#include <iostream>
#include <vector>
#include <iomanip>
#include <stdexcept>
using namespace std;
void outputVector(const vector <int> &);
void inputVector(vector<int> &);
int main(int argc, const char * argv[]) {
// declare two vectors
vector<int> integers1(7);//7-element vector<int>
vector<int> integers2(10);//10-element vector<int>
//print integers1 size and contents
cout<<"Size of vector integers1 is"<<integers1.size()<<"\nvector after initialization:"<<endl;
outputVector(integers1);
//print integers2 size and contents
cout<<"Size of vector integers2 is"<<integers2.size()<<"\nvector after initialization:"<<endl;
outputVector(integers2);
//input and print integers1 and integers2
cout<<"\nEnter 17 integers:"<<endl;
inputVector(integers1);
inputVector(integers2);
cout<<"After input, the vector contain:\n"<<"integers1:"<<endl;
outputVector(integers1);
cout<<"integers2:"<<endl;
outputVector(integers2);
//use inequality operator with vector objects
cout<<"\nEvaluating:integers1!=integers2"<<endl;
if(integers1!=integers2)
cout<<"integers1 and integers2 are not equal"<<endl;
//creat vector integers3 using integers1 as an initializer;print size and contents
vector<int>integers3(integers1);
cout<<"\nSize of vector integers3 is"<<integers3.size()<<"\nvector after initializationg:"<<endl;
outputVector(integers3);
//use overloaded assignment operatot
cout<<"\nAssigning integers2 to integers1:"<<endl;
integers1=integers2;
cout<<"integers1:"<<endl;
outputVector(integers1);
cout<<"integers2:"<<endl;
outputVector(integers2);
//use equality operator with vector objects
cout<<"\nEvaluating:integers1==integers2"<<endl;
if(integers1==integers2)
cout<<"integers1 and integers2 are equal"<<endl;
//use square brackets to use the value at location 5 as an rvalue
cout<<"\nintegers1[5] is"<<integers1[5];
//use square brackets to creat lvalue
cout<<"\n\nAssigning 1000 to integers1[5]"<<endl;
integers1[5]=1000;
cout<<"integers1:"<<endl;
outputVector(integers1);
//attempt to use out-of-range subscript
try
{
cout<<"\nAttempt to display integers1.at(15)"<<endl;
cout<<integers1.at(15)<<endl;
}
catch (out_of_range &ex)
{
cerr<<"An exception occurred:"<<ex.what()<<endl;
}
//changing the size of a vector
cout<<"\nCurrent integers3 size is:"<<integers3.size()<<endl;
integers3.push_back(1000);
cout<<"New integers3 size is:"<<integers3.size()<<endl;
cout<<"integers3 now contains:";
outputVector(integers3);
return 0;
}
void outputVector(vector<int> &array)
{
for(int item: array)
cout<<item<<" ";
cout<<endl;
}
void inputVector(vector<int> &array)
{
for(int &item: array)
cin>>item;
}
|
|