c++ STL 库编程 Vector

#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;
}


(未完待续…)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值