From Electron Cloud
Revision as of 04:31, 15 June 2015 by Ecloud (Talk | contribs)

Jump to: navigation, search

Stringify a define

If you would like to pass a string into a define via the compiler -D directive, but need to use it as if it was a quoted #define, it takes a pair of macros (verified to work on g++ and also Visual Studio):

#define STRINGIFY_IMPL(S) #S
#define STRINGIFY(s) STRINGIFY_IMPL(s)

then it can be used like this:

QFile uiFile(":" STRINGIFY(UI_FILE));

and in the .pro file if using Qt:

DEFINES += UI_FILE="some.ui"

so when it's compiled:

g++ foo.cpp -DUI_FILE=some.ui ...

(oh noes, it's DUI!)

Find range of true values in a std::vector<bool>

std::vector<bool> m_vec;

void update(int index, bool value)
{
    if (index < 0)
        return;
    if (uint(index) >= m_vec.size())
        m_vec.resize(index * 2 + 1);
    m_vec[index] = visible;
}

int firstTrueIndex() const
{
    auto found = std::find(m_vec.begin(), m_vec.end(), true);
    if (found == std::end(m_vec))
        return -1;
    return found - m_vec.begin();
}

int lastTrueIndex() const
{
    auto found = std::find(m_vec.rbegin(), m_vec.rend(), true);
    if (found == m_vec.rend())
        return -1;
    return m_vec.rend() - found;
}