Skip to content

Instantly share code, notes, and snippets.

@torazuka
Created January 23, 2012 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torazuka/487eb4f53eb8bb1b3e43 to your computer and use it in GitHub Desktop.
Save torazuka/487eb4f53eb8bb1b3e43 to your computer and use it in GitHub Desktop.
Chapter20_drill_PPPUC++
#include "../../std_lib_facilities.h"
/* PPPUC Chapter20 drill */
// drill(6)
template<class Iter1, class Iter2> Iter2 copy0(Iter1 f1, Iter1 e1, Iter2 f2)
{
if(f1 == e1) { return f2; }
Iter2 cmp = f2 + (e1 - f1);
for(Iter1 ite = f1; ite != e1; ++ite){
*f2 = *ite;
if(f2 != cmp){
++f2;
} else {
break;
}
}
return f2;
}
int main(){
int ai[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // drill(1)
vector<int> vi(10); // drill(2)
for(int i = 0; i < 10; ++i){
vi[i] = i;
}
list<int> li(0); // drill(3)
for(int i = 0; i < 10; ++i){
li.push_back(i);
}
// drill(4)
int c_ai[] = { 0 };
vector<int> c_vi(10);
list<int> c_li(10);
// drill(5)
for(int i = 0; i < 10; ++i){
int tmp = ai[i];
ai[i] = tmp + 2;
}
for(vector<int>::iterator ite = vi.begin(); ite != vi.end(); ++ite){
int tmp = *ite;
*ite = tmp + 3;
}
for(list<int>::iterator ite = li.begin(); ite != li.end(); ++ite){
int tmp = *ite;
*ite = tmp + 5;
}
// test for drill(5)
cout << "int[]: ";
for(int i = 0; i < 10; ++i){
cout << ai[i] << " ";
}
cout << endl;
cout << "vector<int>: ";
for(vector<int>::iterator ite = vi.begin(); ite != vi.end(); ++ite){
cout << *ite << " ";
}
cout << endl;
cout << "list<int>: ";
for(list<int>::iterator ite = li.begin(); ite != li.end(); ++ite){
cout << *ite << " ";
}
cout << endl;
// test for drill(6): list to list
vector<int>::iterator begin = vi.begin();
vector<int>::iterator end = vi.end();
vector<int> vi2(10);
vector<int>::iterator ite_vi2 = vi2.begin();
vector<int>::iterator result = copy0(begin, end, ite_vi2);
for(vector<int>::iterator ite = ite_vi2; ite != result; ++ite){
cout << *ite << " ";
}
cout << endl;
// drill(7)
copy(&ai[0], &ai[9], vi.begin());
copy(li.begin(), li.end(), &ai[0]);
// test for drill(7)
for(vector<int>::iterator ite = vi.begin(); ite != vi.end(); ++ite){
cout << *ite << " ";
}
cout << endl;
for(int i = 0; i < 10; ++i){
cout << ai[i] << " ";
}
cout << endl;
// drill(8)
int t1 = 3;
vector<int>::iterator viite = find(vi.begin(), vi.end(), t1);
if(viite == vi.end()){
cout << t1 << " is not found." << endl;
} else {
cout << t1 << " is at " << viite - vi.begin() << endl;
}
int t2 = 27;
list<int>::iterator liite = find(li.begin(), li.end(), t2);
if(liite == li.end()){
cout << t2 << " is not found." << endl;
} else {
int c = 0;
while(liite != li.begin()){
--liite;
++c;
}
cout << t2 << " is at " << c << endl;
}
keep_window_open();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment