I have written the code to successfully pass four out of five tests for the “Robot Name” exercise, but I can’t seem to get through the last test. This fifth test is supposed to make sure that even if we have 1000 robots, each of their names will be different. And that’s not the case in my case. Here is the content of my robot_name.h:
{
robot_name::robot robot;
unordered_set<string> names;
names.insert(robot.name());
for (int i = 0; i < 1000; ++i) {
robot.reset();
REQUIRE(names.count(robot.name()) == 0);
REQUIRE(validate_name(robot.name()));
names.insert(robot.name());
}
}
And I fail the test with the following:
FAILED:
REQUIRE( names.count(robot.name()) == 0 )
with expansion:
1 == 0
at /tmp/robot-name/robot_name_test.cpp:60
Which makes me think one of the robot names is not unique. My first thought was to keep track of every robot name by putting it into a vector, and if such a name already exists in the vector, I have to reset() the name. If the new name is unique, we are done naming this robot. Otherwise, I reset() it again until the name is unique.
My problem is that I can’t seem to figure out how to keep track of robot names. Is there a way for me to deal with things belonging to several objects of the class in the class definition?
A class in CPP can have behavior and data that belong to the class, and not object instances. These static or class variables can be seen by object instances though the opposite isn’t generally true. So you could have a container structure defined in your class definition, and then check this before you issue a new name. A Set only contains unique values so in reset(), you can check for presence, and get a new name value before setting m_name
class robot {
…
private:
static std::unordered_setstd::string names{};
(yes, I decided to go ahead with the vector instead of the unordered_set).
And with this version of robot_name.h I’m able to run it locally on my PC. But I get an error when running from the Exercism editor:
We received the following error when we ran your code:
wasm-ld: error: duplicate symbol: robot_name::robot::s_allNames
>>> defined in CMakeFiles/robot-name.dir/robot_name_test.cpp.o
>>> defined in CMakeFiles/robot-name.dir/robot_name.cpp.o
c++: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [CMakeFiles/robot-name.dir/build.make:115: robot-name] Error 1
make[1]: *** [CMakeFiles/Makefile2:85: CMakeFiles/robot-name.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
Anyway this SO question gave me a hint: the second line
std::vector<std::string> robot::s_allNames{};
had to be in the source file and not in the header (though on my computer it works even if this line is in the header). So I moved it to the robot_name.cpp and it solved my problem. And thus the exercise is now solved. Many thanks to you and Steve for taking a look!