c++primer 3.4練習題

3.4 迭代器介紹

3.4.1 使用迭代器

3.21

#include<vector>
#include<iostream>
#include<string>
using namespace std;

int main(){
	vector<int> v1;
	vector<int> v2(10);
	vector<int> v3(10,42);
	vector<int> v4{10};
	vector<int> v5{10,42};
	vector<vector<int>> v{v1,v2,v3,v4,v5};
	vector<string> v6{10};
	vector<string> v7{10 , "hi"};
	vector<vector<string>> vv{v6,v7};
	for(auto it = v.cbegin(); it != v.cend(); ++it){
		for(auto it2 = (*it).cbegin(); it2 != (*it).cend(); ++it2){
			cout<<*it2<<" ";
		}
		cout<<endl;
		/*爲什麼用(*it): 
		As the error states, you are calling begin() on a std::vector<double>::iterator.
		You should call that on a std::vector<double>, so that it could return you a std::vector<double>::iterator.
		*/
	} 
	for(auto it = vv.cbegin(); it != vv.cend(); ++it){
		for(auto it2 = (*it).cbegin(); it2 != (*it).cend(); ++it2){
			cout<<*it2<<" ";
		} 
		cout<<endl;
	}
	return 0;
} 
/*

0 0 0 0 0 0 0 0 0 0
42 42 42 42 42 42 42 42 42 42
10
10 42

hi hi hi hi hi hi hi hi hi hi
*/

3.22

#include<vector>
#include<iostream>
#include<string>
using namespace std;

int main(){
	vector<string> test;
	string line;
	while(getline(cin,line)){
		test.push_back(line);
	}
	for(auto it = test.begin(); it != test.end() && !it->empty(); ++it){
		//輸出test每一行,直到遇到空白行爲止。 
		for(auto it2 = it->begin(); it2 != it->end(); ++it2)
			*it2 = toupper(*it2);
		cout<<*it<<endl; 
	}
    return 0;
} 
/*
ksjfsjfjls
sdfjsjfl
sdoifjdsoijgofjdgspgojospdjsp.ds jodijo jo ojo
ssd sd

jfod
^Z
KSJFSJFJLS
SDFJSJFL
SDOIFJDSOIJGOFJDGSPGOJOSPDJSP.DS JODIJO JO OJO
SSD SD
*/

3.23

#include<vector>
#include<iostream>
#include<string>
using namespace std;

int main(){
	vector<int> a(10,2);
	for(auto i = a.begin(); i != a.end(); ++i){
		*i = (*i)*2;
		cout<<*i<<' ';
	}
} 
//4 4 4 4 4 4 4 4 4 4

3.4.2 迭代器運算

3.24

#include<vector>
#include<iostream>
#include<string>
using namespace std;

int main(){
	vector<int> a;
	int b;
	while(cin>>b){
		a.push_back(b);
	}
	auto beg = a.begin();
	auto end = a.end()-1;
	while(beg<=end){
		if(beg==end) 
			cout<<*beg;
		else
			cout<<*beg + *end;
		beg++;
		end--;
		cout<<' ';
	}
	return 0;
} 
/*
1
2
3
4
^Z
5 5
*/
/*
1
2
3
4
5
^Z
6 6 3
*/

3.25

#include<vector>
#include<iostream>
#include<string>
using namespace std;

int main(){
	vector<unsigned> scores(11,0);
	unsigned grade;
	auto i = scores.begin();
	while(cin>>grade){
		if(grade <= 100)
			*(i + grade/10)+=1;
	}
	for(auto i = scores.begin(); i != scores.end(); ++i){
		cout<<*i<<" ";
	}
	return 0;
} 
/*
42 65 95 100 39 67 95 76 88 76 83 92 76 93
^Z
0 0 0 1 1 0 2 3 2 4 1
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章