- 1
- 2
auto highPriority = static_cast<bool>(features(w)[5]);
// Тип features(w) - std::vector<bool>
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+4
auto highPriority = static_cast<bool>(features(w)[5]);
// Тип features(w) - std::vector<bool>
Скотт Майерс. Эффективный и современный С++.
+4
enum SomeEnum
{
// ...
SomeShit = 0xD6,
// ...
};
// ....
Byte opcode = ReadSomeShit<Byte>(); // функция читающая raw memory в нужном представлении
// из raw memory считано значение эквивалентное 0xD6
// ...
if (opcode == SomeShit) // условие не выполнилось
{
// do stuff
}
// ...
почему? а потому что кто додумался до
typedef char Byte;
который (хоть и не обязан быть, но) знаковый
и даже сраного ворнинга не выдало
причина правда обнаружилась достаточно быстро, ибо в дебагере в opcode красовалось -42 а в SomeShit 214
https://ideone.com/02TpT7 на первый взгляд вызывает когнитивный диссонанс
обожаю кресты
+2
#include <iostream>
#include <stdexcept>
using namespace std;
class Exception : std::runtime_error
{
public:
Exception( std::string const & what ) : std::runtime_error(what)
{
}
};
int main( )
{
try
{
throw Exception("Exception");
}
catch ( std::exception const & e )
{
std::cerr << e.what() << std::endl;
}
catch(...)
{
std::cerr << "..." << std::endl;
}
return 0;
}
+8
#include <iostream>
using namespace std;
class Boolean {
public:
Boolean() : m_flag(false), m_val(0) {}
Boolean(bool flag) : m_flag(flag), m_val(0) {}
Boolean(bool flag, int val) : m_flag(flag), m_val(val) {}
Boolean operator || (int val) {
return Boolean(m_flag || val == m_val, m_val);
}
operator bool() { return m_flag; }
private:
bool m_flag;
int m_val;
};
class Integer {
public:
Integer() : m_val(0) {}
Integer(int val) : m_val(val) {}
operator int() { return m_val; }
Boolean operator == (int val) { return Boolean(val == m_val, m_val); }
Boolean operator == (const Integer & val) { return Boolean(val.m_val == m_val, m_val); }
private:
int m_val;
};
int main() {
Integer a(10);
cout << bool(a == 15 || 10) << endl;
cout << bool(a == 15 || 11) << endl;
cout << bool(a == 15 || 11 || 13 || 11 || 0 || 10 || 5) << endl;
cout << bool(a == 15 || 11 || 13 || 11 || 0 || 9 || 5) << endl;
return 0;
}
https://ideone.com/xwMvx7
+3
Point3D& operator /= (const float f) { x/=f; y/=f; z/=f; return *this; }
ебать я лох
+3
template<class... Bases>
struct MaminVisitor: public boost::static_visitor<>, public Bases... {
MaminVisitor(Bases&&... bases) : Bases(std::move(bases))... { }
};
template<class Variant, class... F>
void match(Variant &&v, F &&... functors) {
typedef MaminVisitor<typename std::decay<F>::type...> visitor_t;
boost::apply_visitor(visitor_t(std::move(functors)...), std::forward<Variant>(v));
}
int main() {
boost::variant<int, double, std::string> v = "ololo";
match(v,
[&](auto x) {
std::cout << "auto branch " << x << std::endl;
},
[&](double x) {
std::cout << "double branch " << x << std::endl;
}
);
return 0;
}
Сделал няшный матч, а на гцц не конпелируется.
http://ideone.com/J9ulsr
+1
while (cycle) {
#if DEBUG == 1
mvprintw(0, 0, "cn: %i", cn);
mvprintw(all_lines + 7, 0, "max_line: %i\nMaxX: %i\nMaxY: %i", max_line, maxX, maxY);
#endif
if (active_input == 1)
attron(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input != 1)
attron(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (dlgcfg.keys > 1) {
mvprintw(i + 3 + title_fix, left_border_x + 2, " %s ", dlgcfg.f_button.c_str()); // Первая кнопка
} else {
mvprintw(i + 3 + title_fix, maxX / 2 - (dlgcfg.f_button.length() / 2) - 1, " %s ", dlgcfg.f_button.c_str()); // Центровка первой кнопки (Если она одна)
}
if (active_input != 1)
attroff(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (active_input == 1)
attroff(COLOR_PAIR(color_selected) | A_BOLD);
if (dlgcfg.keys == 2) {
if (active_input == 2)
attron(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input != 2)
attron(COLOR_PAIR(dlgcfg.style) | A_BOLD);
mvprintw(i + 3 + title_fix, maxX / 2 + (max_line / 2) - dlgcfg.s_button.length() - 3 - fix, " %s ", dlgcfg.s_button.c_str()); // Вторая кнопка
if (active_input != 2)
attroff(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (active_input == 2)
attroff(COLOR_PAIR(color_selected) | A_BOLD);
}
if (dlgcfg.keys == 3) {
if (active_input == 2)
attron(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input != 2)
attron(COLOR_PAIR(dlgcfg.style) | A_BOLD);
mvprintw(i + 3 + title_fix, s_key_pos - dlgcfg.s_button.length() / 2, " %s ", dlgcfg.s_button.c_str()); // Вторая кнопка
if (active_input != 2)
attroff(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (active_input == 2)
attroff(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input == 3)
attron(COLOR_PAIR(color_selected) | A_BOLD);
if (active_input != 3)
attron(COLOR_PAIR(dlgcfg.style) | A_BOLD);
mvprintw(i + 3 + title_fix, maxX / 2 + (max_line / 2) - dlgcfg.t_button.length() - 3 - fix, " %s ", dlgcfg.t_button.c_str()); // Вторая кнопка
if (active_input != 3)
attroff(COLOR_PAIR(dlgcfg.style) | A_BOLD);
if (active_input == 3)
attroff(COLOR_PAIR(color_selected) | A_BOLD);
}
cn = getch();
switch (cn) {
case CtrlF1: info_win();
break;
case KEY_LEFT: if (active_input != 1)
active_input--;
break;
case KEY_RIGHT: if (active_input != dlgcfg.keys)
active_input++;
break;
case TAB_KEY: if (active_input != dlgcfg.keys) {
active_input++;
} else {
active_input = 1;
}
break;
case 27: delete [] array;
return 0;
break;
case '\n': if (active_input != 0) {
delete [] array;
return active_input;
}
break;
}
И ещё ~400 строк такой же дичи)
Даже если интерфейс кажется вам милым и опрятным, не распространяйте свои догадки на реализацию...
+5
ostringstream s;
...
- return s.str();
+ return std::move(s.str());
соптимизировано
0
...
scr[6][0] = '\\'; scr[6][1] = '\\';//прорисовка корабля
scr[7][0] = '3'; scr[7][1] = '='; scr[7][2] = '=';
scr[8][0] = '/'; scr[8][1] = '/';
...
if (_kbhit())//если клавиша была нажата
{
control = _getch();//переменная примет ее значение
if (control == 224)
control = _getch();
}
if (control == 72)//при движении корабля вверх
if (scr[2][0] == '\\' || scr[3][0] == '\\' && scr[2][0] == '¤' || scr[3][1] == '\\' && scr[2][1] == '¤')//если корабль врезался в верхнее поле - игра окончена
if (lifes > 1)
{
cout << '\a';
lifes--;
weaponPos = 7;
GameStart(scr, lifes, &timer);
Sleep(1000);
}
else
GameOver(odometer);
else
{
for (int i = 2; i < 13; i++)//корабль смещается на элемент выше
for (int j = 0; j < 49; j++)
if (scr[i][j] == '3' || scr[i][j] == '\\' || scr[i][j] == '=' || scr[i][j] == '/')
{
scr[i - 1][j] = scr[i][j];
scr[i][j] = ' ';
}
weaponPos--;
}
if (control == 80)//при движении корабля вниз
if (scr[12][0] == '/' || scr[11][0] == '/' && scr[12][0] == '¤' || scr[11][1] == '/' && scr[12][1] == '¤')//если корабль врезался в нижнее поле - игра окончена
if (lifes > 1)
{
cout << '\a';
lifes--;
weaponPos = 7;
GameStart(scr, lifes, &timer);
Sleep(1000);
}
else
GameOver(odometer);
else
{
for (int i = 12; i >= 2; i--)//корабль смещается на элемент вниз
for (int j = 0; j < 49; j++)
if (scr[i][j] == '3' || scr[i][j] == '\\' || scr[i][j] == '=' || scr[i][j] == '/')
{
scr[i + 1][j] = scr[i][j];
scr[i][j] = ' ';
}
weaponPos++;
}
...
И многое другое на https://habrahabr.ru/post/304448/
+1
std::deque<std::pair<int, int>> Pathing::findPath(int sx, int sy, int fx, int fy) const
{
std::list<Node> openNodes;
std::list<Node> closeNodes;
const Node startNode{nullptr, sx, sy, 0, 0, 0};
openNodes.push_back(startNode);
auto cells = gameMap->getCells();
auto findNode = [](auto&& list, int x, int y)
{
return std::find_if(std::begin(std::forward<decltype(list)>(list)),
std::end(std::forward<decltype(list)>(list)),
[x, y](auto n) {return n.x == x && n.y == y;});
};
auto isNodeInList = [findNode](auto&& list, int x, int y)
{
return findNode(std::forward<decltype(list)>(list), x, y) != list.cend();
};
auto processNode = [&](auto iterCurrentNode, int x, int y)
{
const auto nx = iterCurrentNode->x + x;
const auto ny = iterCurrentNode->y + y;
if (cells[nx][ny].passable && !isNodeInList(closeNodes, nx, ny))
{
const auto G = iterCurrentNode->G + (x && y ? 14 : 10);
const auto H = (std::abs(fx - nx) + std::abs(fy - ny)) * 10;
const auto F = G + H;
auto node = findNode(openNodes, nx, ny);
if (node == openNodes.cend())
{
openNodes.push_back({&(*iterCurrentNode), nx, ny, G, H, F});
if (nx == fx && ny == fy)
return true;
}
else
{
if (G < node->G)
{
node->parent = &(*iterCurrentNode);
node->G = G;
node->H = H;
node->F = F;
}
}
}
return false;
};
while (!openNodes.empty())
{
auto iterMinF = std::min_element(openNodes.cbegin(), openNodes.cend(),
[](auto n1, auto n2) {return n1.F < n2.F;});
closeNodes.push_back(*iterMinF);
auto iter = closeNodes.insert(closeNodes.cend(), *iterMinF);
openNodes.erase(iterMinF);
if (processNode(iter, 1, 0) ||
processNode(iter, 1, 1) ||
processNode(iter, 0, 1) ||
processNode(iter, -1, 1) ||
processNode(iter, -1, 0) ||
processNode(iter, -1, -1) ||
processNode(iter, 0, -1) ||
processNode(iter, 1, -1))
break;
}
auto finalNode = findNode(openNodes, fx, fy);
if (finalNode == openNodes.cend())
return {};
std::deque<std::pair<int, int>> route{{finalNode->x, finalNode->y}};
const Node* temp = finalNode->parent;
while (temp)
{
route.push_front({temp->x, temp->y});
temp = temp->parent;
}
return route;
}