8
\$\begingroup\$

I created an enum for a class and in the constructor I inserted all the enum values into a set. I am wondering if there is a better way anyone can recommend. I feel like there should be, but have been unable to think of one or find one online. I wrote the code in C++ and am using the Boost libraries.

Here is the enum:

class CreateAndUseIniFile {
 std::set<CreateAndUseIniFile::iniFileValues> m_modules;
 enum iniFileValues {
 FIXED_VOLTAGE1,
 FIXED_VOLTAGE2,
 FIXED_VOLTAGE3,
 FIXED_VOLTAGE4
 }
}

and this is the constructor where I add the values

CreateAndUseIniFile::CreateAndUseIniFile() {
 m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE1);
 m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE2);
 m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE3);
 m_modules.insert(CreateAndUseIniFile::FIXED_VOLTAGE4);
} 
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 12, 2014 at 14:28
\$\endgroup\$
1

2 Answers 2

6
\$\begingroup\$

You can iterate over the enum and insert each one individually.

for ( int i = FIXED_VOLTAGE1; i != FIXED_VOLTAGE4; i++ )
{
 m_modules.insert(CreateAndUseIniFile::static_cast<iniFileValues>(i));
}

Note: This will work with your specific case... don't do this if you have enums with set values that contain gaps between enum values.

answered Mar 12, 2014 at 14:48
\$\endgroup\$
2
  • \$\begingroup\$ Thanks, for some reason I thought I couldn't iterate though an enum \$\endgroup\$ Commented Mar 12, 2014 at 16:45
  • \$\begingroup\$ @Aaron No problem. enums are basically just fancy ints. They should only be iterated through during controlled situations like yours. \$\endgroup\$ Commented Mar 12, 2014 at 16:53
2
\$\begingroup\$

As an alternative, you can use Boost Assignment Library. Then you will get something like this:

#include <boost/assign/list_of.hpp>
#include <set>
class CreateAndUseIniFile {
public:
 enum iniFileValues {
 FIXED_VOLTAGE1,
 FIXED_VOLTAGE2,
 FIXED_VOLTAGE3,
 FIXED_VOLTAGE4
 };
 CreateAndUseIniFile() {
 m_modules =
 boost::assign::list_of
 (FIXED_VOLTAGE1)
 (FIXED_VOLTAGE2)
 (FIXED_VOLTAGE2)
 (FIXED_VOLTAGE3)
 (FIXED_VOLTAGE4);
 }
 std::set<CreateAndUseIniFile::iniFileValues> m_modules;
};
answered Mar 15, 2014 at 22:45
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.