CPP

CPP practice questions, page 3 of 9, with answer review and explanations.

Question 11

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); cout<<*max_element(v1.begin(), v1.end()); return 0; } Program outputs:

  1. 3
  2. 1
  3. 6
  4. 10
  5. compilation error

Question 12

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_intersection(t1,t1+5,t2,t2+5,v1.begin()); for_each(v1.begin(), v1.end(), Out (cout));cout<<endl; return 0; } Program outputs:

  1. compilation error
  2. 1 2 3 4 5 6 8 0 0 0
  3. 1 2 3 4 5 6 8 2 1 0
  4. 1 1 2 2 3 4 5 5 6 8
  5. 1 2 5 0 0 0 0 0 0 0

Question 13

What happens when you attempt to compile and run the following code? #include #include #include #include #include using namespace std; void myfunction(int i) { cout v1(t, t + 10); deque d1(t, t + 10); set s1(t, t + 10); for_each(v1.begin(), v1.end(), myfunction); // Line I for_each(d1.begin(), d1.end(), myfunction); // Line II for_each(s1.begin(), s1.end(), myfunction); // Line III return 0; }

  1. program outputs: 10 5 9 6 2 4 7 8 3 1 10 5 9 6 2 4 7 8 3 1 1 2 3 4 5 6 7 8 9 10
  2. program outputs: 10 5 9 6 2 4 7 8 3 1 10 5 9 6 2 4 7 8 3 1 10 5 9 6 2 4 7 8 3 1
  3. program outputs: 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
  4. compilation error in line I
  5. compilation error in line III

Question 14

What happens when you attempt to compile and run the following code? #include #include #include using namespace std; int main() { int t[] = { 10, 5, 9, 6, 2, 4, 7, 8, 3, 1 }; map m; for(int i=0; i p(5,5); map ::iterator it = find(m.begin(), m.end(), p); if (it != m.end()) { cout first<<endl; } else { cout<<"Not found!\n"; } return 0; } Program outputs:

  1. 5
  2. Not found!
  3. 10
  4. compilation error

Question 15

What happens when you attempt to compile and run the following code? #include #include #include #include using namespace std; void myfunction(int i) { cout s1(t, t+10); vector v1(s1.rbegin(), s1.rend()); swap_ranges(s1.begin(), s1.end(), v1.begin()); for_each(v1.begin(), v1.end(), myfunction); for_each(s1.begin(), s1.end(), myfunction); return 0; } Program outputs:

  1. 10 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10
  2. compilation error
  3. 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
  4. 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1
  5. 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1