Question 5 Given an arbitrary definition of a class named Object as abstract dat
ID: 3843470 • Letter: Q
Question
Question 5
Given an arbitrary definition of a class named Object as abstract data type - if a designer wanted to use an associative container like an std::map of the form std::map< Object, int* > - state and explain what important property must be defined for the class Object for it to be usable in the std::map as shown.
Question 6
State what are the 2 problems in the following code (2pts)
Provide a solution for each problem so that the code compiles and runs correctly by adding to this code (3pts)
// ----------------- Quiz question ----------------
#include <iostream>
#include <set>
#include <string>
#include <ctime>
using std::string;
class Employee
{
public:
Employee(const int& n) : m_eid(n) {}
~Employee() {}
int getEmpId() const
{
return m_eid;
}
private:
int m_eid;
};
int main(int argc, char* argv[])
{
using std::cout;
using std::endl;
using std::set;
set mySet;
srand(time(NULL));
unsigned int x = 0;
while (x < 1000)
{
Employee emp( rand() % 1000 + 1 );
mySet.insert( emp );
x++;
}
return 0;
}
Explanation / Answer
Q5)
You have to define operator< for your class or
You can also make a comparator function object class for it, and use that to specialize std::map. To extend your example:
Q6.
// ERROR: use of class template 'set' requires template arguments
//set mySet;
set<Employee> mySet;
// ERROR: to add an user defined Object in Set, you need to oveload operator<
mySet.insert( emp );
bool operator< (const Employee &left, const Employee &right){
return left.getEmpId() < right.getEmpId();
}
// ----------------- Quiz question ----------------
#include <iostream>
#include <set>
#include <string>
#include <ctime>
using std::string;
class Employee
{
public:
Employee(const int& n) : m_eid(n) {}
friend bool operator< (const Employee &left, const Employee &right);
~Employee() {}
int getEmpId() const
{
return m_eid;
}
private:
int m_eid;
};
bool operator< (const Employee &left, const Employee &right){
return left.getEmpId() < right.getEmpId();
}
int main(int argc, char* argv[])
{
using std::cout;
using std::endl;
using std::set;
// ERROR: use of class template 'set' requires template arguments
//set mySet;
set<Employee> mySet;
srand(time(NULL));
unsigned int x = 0;
while (x < 1000)
{
Employee emp(rand() % 1000 + 1 );
// ERROR: to add an user defined Object in Set, you need to oveload operator<
mySet.insert( emp );
x++;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.