From Electron Cloud
Jump to: navigation, search
(Find range of true values in a std::vector)
 
Line 19: Line 19:
  
 
<pre>
 
<pre>
std::vector<bool> m_vec;
+
class Tracker
 
+
void update(int index, bool value)
+
 
{
 
{
    if (index < 0)
+
public:
        return;
+
void update(int index, bool value)
    if (uint(index) >= m_vec.size())
+
{
        m_vec.resize(index * 2 + 1);
+
if (index < 0)
    m_vec[index] = visible;
+
return;
}
+
if (unsigned(index) >= m_vec.size())
 +
m_vec.resize(index * 2 + 1);
 +
m_vec[index] = value;
 +
}
  
int firstTrueIndex() const
+
int firstIndex(bool val)
{
+
{
    auto found = std::find(m_vec.begin(), m_vec.end(), true);
+
auto found = std::find(std::begin(m_vec), std::end(m_vec), val);
    if (found == std::end(m_vec))
+
if (found == std::end(m_vec))
        return -1;
+
return -1;
    return found - m_vec.begin();
+
return found - m_vec.begin();
}
+
}
  
int lastTrueIndex() const
+
int lastIndex(bool val)
{
+
{
    auto found = std::find(m_vec.rbegin(), m_vec.rend(), true);
+
auto found = std::find(m_vec.rbegin(), m_vec.rend(), true);
    if (found == m_vec.rend())
+
if (found == m_vec.rend())
        return -1;
+
return -1;
    return m_vec.rend() - found;
+
return m_vec.rend() - found;
}
+
}
 +
 
 +
std::vector<bool> m_vec;
 +
};
 
</pre>
 
</pre>

Latest revision as of 04:45, 15 June 2015

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>

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

	int firstIndex(bool val)
	{
		auto found = std::find(std::begin(m_vec), std::end(m_vec), val);
		if (found == std::end(m_vec))
			return -1;
		return found - m_vec.begin();
	}

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

	std::vector<bool> m_vec;
};