CPP practice questions, page 4 of 9, with answer review and explanations.
Question 16
What happens when you attempt to compile and run the following code? #include #include #include using namespace std; int main(){ int t[] ={ 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 }; list v(t, t+10); set s1(v.begin(),v.end()); if (s1.count(3) == 2) { s1.erase(3); } for(set ::iterator i=s1.begin();i!= s1.end(); i++) { cout<<*i<<" "; } return 0; }
program outputs: 1 2 3 4 5
program outputs: 1 2 4 5
program outputs: 1 1 2 2 3 4 4 5 5
program outputs: 1 1 2 3 3 4 4 5 5
compilation error
Question 17
What happens when you attempt to compile and run the following code? #include #include #include #include using namespace std; template struct Out { ostream & out; Out(ostream & o): out(o){} void operator() (const T & val ) { out v1(t, t+10); vector v2(10); transform(v1.begin(), v1.end(), v2.begin(), bind2nd(ptr_fun (Add),1)); vector ::iterator it = find_if(v2.begin(), v2.end(),bind2nd(equal_to (),10)); cout<<*it<<endl; return 0; } Program outputs:
false
true
10
0
compilation error
Question 18
What happens when you attempt to compile and run the following code? #include #include #include #include using namespace std; void myfunction(int i) { cout d1(t, t+10); vector v1(d1.rbegin(), d1.rend()); sort(d1.begin(), d1.end()); swap_ranges(v1.begin(), v1.end(), d1.begin()); for_each(v1.begin(), v1.end(), myfunction); for_each(d1.begin(), d1.end(), myfunction); return 0; } Program outputs:
10 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10
compilation error
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 1 3 8 7 4 2 6 9 5 10
1 3 8 7 4 2 6 9 5 10 1 2 3 4 5 6 7 8 9 10
Question 19
What happens when you attempt to compile and run the following code? #include #include #include using namespace std; template struct Out { ostream & out; Out(ostream & o): out(o){} void operator() (const T & val ) { out v1(10); sort(t1, t1+5); sort(t2, t2+5); set_union(t1,t1+5,t2,t2+5,v1.begin()); for_each(v1.begin(), v1.end(), Out (cout));cout<<endl; return 0; } Program outputs:
3 2 4 1 5 6 8 2 1 0
1 2 3 4 5 6 8 2 1 0
1 1 2 2 3 4 5 5 6 8
1 2 3 4 5 6 8 0 0 0
compilation error
Question 20
What happens when you attempt to compile and run the following code? #include #include #include using namespace std; template struct Out { ostream & out; Out(ostream & o): out(o){} void operator() (const T & val ) { out v1(t,t+10); sort(v1.begin(), v1.end(), greater ()); cout<<min_element(v1.begin(), v1.end()); return 0; } Program outputs: