7
\$\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);
} 
\$\endgroup\$
1
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.

\$\endgroup\$
2
  • \$\begingroup\$ Thanks, for some reason I thought I couldn't iterate though an enum \$\endgroup\$ – Aaron Mar 12 '14 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\$ – BenVlodgi Mar 12 '14 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;
};
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.