CPP

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

Question 21

What will happen when you attempt to compile and run the code below, assuming that you enter the following sequence: 1 2 3 end ? #include #include #include #include using namespace std; template struct Out { ostream & out; Out(ostream & o): out(o){} void operator() (const T & val ) {out l; for( ; !cin.bad() ; ) { int i; cin>>i; l.push_back(i); } for_each(l.begin(), l.end(), Out (cout)); return 0; } Program will output:

  1. 1 2 3
  2. 1 2 3 end
  3. 1
  4. compilation error
  5. program runs forever without output

Question 22

What happens when you attempt to compile and run the following code? #include #include #include using namespace std; template void print(T start, T end) { while (start != end) { std::cout v; multiset s; for(int i=10; i>0; i??) { v.push_back(i); s.push_back(i); } print(v.begin(), v.end()); print(s.begin(), s.end());cout<<endl; return 0; }

  1. program outputs: 10 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10
  2. program outputs: 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1
  3. program outputs: 10 9 8 7 6 5 4 3 2 1 and unpredictable sequence of numbers range 1 to 10
  4. compilation error

Question 23

What happens when you attempt to compile and run the following code? #include #include using namespace std; int main() { int t[] = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 }; string s[] = { "one", "one", "two", "two", "three","three", "four", "four", "five", "five"}; map m; for (int i = 0; i (t[i], s[i])); } for (map ::iterator i = m.begin(); i != m.end(); i++) { cout first << " "; } return 0; }

  1. program outputs: 1 2 3 4 5
  2. compilation error
  3. program outputs: 1 1 2 2 3 3 4 4 5 5
  4. program outputs: one two three four five
  5. program outputs: one one two two three three four four five five

Question 24

What happens when you attempt to compile and run the following code? #include #include #include using namespace std; class B { int val; public: B(int v):val(v){} int getV() const {return val;} bool operator struct Out { ostream & out; Out(ostream & o): out(o){} void operator() (const T & val ) { out d1(t, t+10); sort(d1.begin(), d1.end()); deque ::iterator it = upper_bound(d1.begin(), d1.end(), B(4), greater ()); for_each(it, d1.end(), Out (cout)); cout<<endl; return 0; } Program outputs:

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

Question 25

Which stack initialization (line numbers) are correct? Choose all that apply. #include #include #include #include #include using namespace std; int main() { deque mydeck; list mylist; vector myvector; stack first;// Line I stack second(mydeck);// Line II stack third(second);// Line III stack > fourth(mylist);// Line IV stack > fifth(myvector);// Line V return 0; }

  1. line I
  2. line II
  3. line III
  4. line IV
  5. line V