C++ Vector

This quiz tests your knowledge of C++ vector container and its associated operations. It contains 10 MCQs

Last Updated :
Discuss
Comments

Question 1

Which of the following is the correct way to declare an empty vector of integers named my_vec?

  • vector<int> my_vec;

  • vector int my_vec;

  • int vector my_vec;

  • vector<int> my_vec[];

Question 2

Predict the output of this program:

C++
#include <iostream> #include <vector> using namespace std;  int main() {     vector<int> v = {1, 2, 3};     cout << v.size() << " " << v.capacity();     return 0; } 


  • 3 3

  • 0 3

  • 3 0

  • 3 4

Question 3

What will the following code print?

C++
#include <iostream> #include <vector> using namespace std; int main() {     vector<int> v = {1, 2, 3, 4, 5};     v.resize(3);     cout << v.size() << " " << v[2];     return 0; } 


  • 5 3

  • Error

  • 3 5

  • 3 3

Question 4

What will the following code print?

C++
#include <iostream> #include <vector> using namespace std; int main() {     vector<int> v = {1, 2, 3, 4, 5};     for (int x : v)         x = x + 2;              for (int x : v)         cout << x << " ";     return 0; } 
  • 1 2 3 4 5

  • 2 4 6 8 10

  • 2 4 5 6 7

  • Compiler Error

Question 5

What will the following code print?

C++
#include <iostream> #include <vector> using namespace std; int main() {     vector<int> v = {1, 2, 3};     vector<int>::iterator it = v.begin();     cout << (it + 1);     return 0; } 


  • Error

  • 1

  • 2

  • 3

Question 6

What will the following code print?

C++
#include <iostream> #include <vector> using namespace std; int main() {     vector<int> v1 = {1, 2, 3};     vector<int> v2;     v2 = v1;     v1[0] = 10;     cout << v2[0];     return 0; } 


  • Error

  • 3

  • 2

  • 1

Question 7

What is the difference between v.size() and v.capacity()?





  • They are always equal.

  • size() is the number of elements, capacity() is the allocated storage.

  • size() is the allocated storage, capacity() is the number of elements.

  • They are unrelated.

Question 8

How do you access the element at index 2 in a vector named my_vector?





  • my_vector.at(2)

  • my_vector[2]

  • my_vector(2)

  • None of the Above.

Question 9

Which function is used to remove the last element from a vector?

  • remove_last()

  • delete_last()

  • pop_back()

  • erase_last()

Question 10

What does the push_back() function do to a vector?

  • Adds an element to the end.

  • Adds an element to the beginning.

  • Removes the last element.

  • Inserts an element at a specific index.

Tags:

There are 11 questions to complete.

Take a part in the ongoing discussion