C Plus Plus Miscellaneous - Study Mode

[#591] What will be the output of the following C++ code? #include <iostream>
#include <algorithm>
#include <vector>

using namespace std

int main ()
{
vector<int> v = {4,2,10,5,1,8}

sort(v.begin(), v.end())

if (binary_search(v.begin(), v.end(), 4))
cout << "found.
"

else
cout << "not found.
"

return 0

}
Correct Answer

(A) found.

[#592] What will be the output of the following C++ code? #include <iostream>
#include <string>
using namespace std

int main()
{
string s = "a long string"

s.insert(s.size() / 2, " * ")

cout << s << endl

return 0

}
Correct Answer

(C) Depends on compiler

[#593] What will be the output of the following C++ code? #include <iostream>
#include <vector>

using namespace std

int main()
{
vector<int> v

for (int i = 1

i <= 5

i++)
v.push_back(i)

for(int i=0

i<v.size()

i++)
cout<<v[i]<<" "

cout<<endl

v.assign(3, 8)

for(int i=0

i<v.size()

i++)
cout<<v[i]<<" "

cout<<endl

return 0

}
Correct Answer

(A) 1 2 3 4 5 8 8 8

[#594] What will be the output of the following C++ code? #include <iostream>
#include <vector>
using namespace std

int main ()
{
vector<int> myvector

myvector.push_back(78)

myvector.push_back(16)

myvector.front() += myvector.back()

cout << myvector.front() << '
'

return 0

}
Correct Answer

(C) 94

[#595] What will be the output of the following C++ code? #include <iostream>
#include <vector>
using namespace std

class Component
{
public:
virtual void traverse() = 0

}

class Leaf: public Component
{
int value

public:
Leaf(int val)
{
value = val

}
void traverse()
{
cout << value << ' '

}
}

class Composite: public Component
{
vector < Component * > children

public:
void add(Component *ele)
{
children.push_back(ele)

}
void traverse()
{
for (int i = 0

i < children.size()

i++)
children[i]->traverse()

}
}

int main()
{
Composite containers[4]

for (int i = 0

i < 4

i++)
for (int j = 0

j < 3

j++)
containers[i].add(new Leaf(i *3+j))

for (int k = 1

k < 4

k++)
containers[0].add(&(containers[k]))

for (int p = 0

p < 4

p++)
{
containers[p].traverse()

}
}
Correct Answer

(D) 0 1 2 3 4 5 6 7 8 9 10 11 3 4 5 6 7 8 9 10 11