Here is a listing of C++ Programming quiz on “Allocators” along with answers, explanations and/or solutions:
1. Where are allocators used?
a) Allocation of memory
b) Deallocation of memory
c) Used for pointers
d) Both Allocation & Deallocation of memory
Answer: d
Clarification: Allocators handle all the request for allocation and deallocation of memory for the container.
2. Where are allocators implemented?
a) Template library
b) Standard library
c) C++ code library
d) String library
Answer: b
Clarification: Allocators are implemented in C++ standard library but it is used for C++ template library.
3. Which operator is used to allocate the memory?
a) =
b) +
c) new
d) free
Answer: c
Clarification: The default allocator uses operator new to allocate memory.
4. What will be the output of the following C++ code?
-
#include -
#include -
#include -
using namespace std;
-
int main ()
-
{ -
int numbers[] = {1, 5, 4, 5};
-
pair <int*, ptrdiff_t> result = get_temporary_buffer<int>(4);
-
if (result.second > 0)
-
{ -
uninitialized_copy (numbers, numbers + result.second, result.first);
-
sort (result.first, result.first + result.second);
-
for (int i = 0; i < result.second; i++)
-
cout << result.first[i] << " ";
-
return_temporary_buffer (result.first);
-
} -
return 0;
-
}
a) 1 5 5 4
b) 5 5 4 1
c) 1 4 5 5
d) 1 4 5 2
Answer: c
Clarification: In this program, We are sorting the array by using the allocator.
Output:
$ g++ all.cpp $ a.out 1 4 5 5
5. What will be the output of the following C++ code?
-
#include -
#include -
#include -
using namespace std;
-
int main ()
-
{ -
string numbers[] = {"steve", "jobs"};
-
pair <string*, ptrdiff_t> result = get_temporary_buffer<string>(2);
-
if (result.second>0)
-
{ -
uninitialized_copy ( numbers, numbers + result.second, result.first );
-
for (int i = 0; i < result.second; i++)
-
cout << result.first[i] << " ";
-
return_temporary_buffer(result.first);
-
} -
return 0;
-
}
a) steve
b) jobs
c) jobs steve
d) steve jobs
Answer: d
Clarification: In this program, We are storing the string and retrieving the string by using get_temporary_method.
Output:
$ g++ all1.cpp $ a.out steve jobs
