bachra04
asked on
compare a struct with standard list
Hi Experts,
I have the following struct in c++ :
typedef struct
{
std::string type;
std::string name;
std::list<std::string> contacts
bool connected;
} clientDetail;
I have 2 questions :
1- how to initialize the struct to null;
2 - I need to create a method that compares two client Detail structs, how should I do that ? Do I need to allocate dynamic memory for the list ?
Thanks,
B.L.
I have the following struct in c++ :
typedef struct
{
std::string type;
std::string name;
std::list<std::string> contacts
bool connected;
} clientDetail;
I have 2 questions :
1- how to initialize the struct to null;
2 - I need to create a method that compares two client Detail structs, how should I do that ? Do I need to allocate dynamic memory for the list ?
Thanks,
B.L.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I assume it will be the same for overloading the assignment operator ?
ASKER
I mean do I need to overload assignment operator or the default = operator works fine between two standard lists.
Um, nor sure what you mean - overloading the assignment opeator is only nessecary for assignments, not for comparisons. But, in a bigger picture, it'd be similar.
In your specific example, the string type is automatically initialized to an empty string, the list to an empty list. The only problem is with bool that is a kind of lower-level object. It should have one of false/true values. You can fill it with zero somehow to initialize it to false. However, it is better to initialize it explicitly to false instead. Using the C++11 standard, you can modify your last element definition to bool connected { false }; (and do not forget to add the semicolon to the previous line).
A struct is basically treated as class with public elements. You should probably convert it to the class as it does not help anything to keep it struct.
For the comparison, the two approaches are usually used: 1) write a function that takes the two compared objects (usually constant references to them), 2) write a method of the same class that compares itself with the passed argument. Understanding the second approach, you can add syntactic sugar and overload the wanted operator.