#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<double> a;
vector<double>::const_iterator i;
for(int i=1;i<10;i++){
a.push_back(i);
}
for(i=a.begin();i!=a.end();i++){
cout<<(*i)<<endl;
}
system("pause");
return 0;
}
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<class T>
struct print{
void operator()(T& x)const
{
if(x%2==0){
cout <<x<<" ";
}
}
};
int main(){
cout<<"使用STL"<<endl;
cout<<endl;
vector<int> a;
for(int i=0;i<10;i++){
a.push_back(i);
}
vector<int>::iterator aBegin,aEnd;
aBegin=a.begin();
aEnd=a.end();
cout<<"输出所有元素:"<<endl;
for(;aBegin!=aEnd;aBegin++){
cout<<*aBegin<<" ";
}
cout<<endl;
cout<<"输出偶数元素:"<<endl;
aBegin=a.begin();
for_each(aBegin,aEnd,print<int>());
cout <<endl<<endl;
system("pause");
return 0;
}
把字符串传到一个字符变量中,然后每次显示变量中的一个字符:
#include <vector>
#include <iostream>
using namespace std;
char *sentenceArray = "Hello world";//为一个字符数组,以“\0”结束
int main(){
vector <char> vec;
vector <char>::iterator vi;//为字符数组定义一个游标iterator
char* cptr=sentenceArray;//把一个指针指向“hello world”字符串
while(*cptr!='\0'){
vec.push_back(*cptr);cptr++;
}
for(vi=vec.begin();vi!=vec.end();vi++){
cout <<*vi;
}
cout<<endl;
system("pause");
return 0;
}
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <string>
using namespace std;
int main(void)
{
vector<string> v1;
ifstream file("d://1.txt");
if(file.fail()){
cout <<"failed to open .";
return 1;
}
copy(istream_iterator<string>(file),istream_iterator<string>(),inserter(v1,v1.begin()));
copy(v1.begin(),v1.end(),ostream_iterator<string>(cout," "));
cout <<endl;
system("pause");
return 0;
}
利用vector容器定义二位数组:
#include<stdio.h>
#include<vector>
#include <iostream>
using namespace std;
int main()
{
int i = 0, j = 0;
vector< vector<int> > Array;
vector< int > line;
for( j = 0; j < 10; j++ )
{
Array.push_back( line );//要对每一个vector初始化,否则不能存入元素。
for ( i = 0; i < 9; i++ )
{
Array[ j ].push_back( i );
}
}
for( j = 0; j < 10; j++ )
{
for( i = 0; i < Array[ j ].size(); i++ )
{
cout << Array[ j ][ i ] << " ";
}
cout<< endl;
}
system("pause");
return 0;
}
(未完待续…)