From Electron Cloud
Jump to: navigation, search
(New page: ==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...)
 
(Find range of true values in a std::vector)
 
(2 intermediate revisions by the same user not shown)
Line 15: Line 15:
  
 
(oh noes, it's DUI!)
 
(oh noes, it's DUI!)
 +
 +
==Find range of true values in a std::vector<bool>==
 +
 +
<pre>
 +
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;
 +
};
 +
</pre>

Latest revision as of 05: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;
};