- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
#include <iostream>
struct Test {
operator auto() -> bool { return true; }
};
int main() {
std::cout << std::boolalpha << Test() << std::endl;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+7
#include <iostream>
struct Test {
operator auto() -> bool { return true; }
};
int main() {
std::cout << std::boolalpha << Test() << std::endl;
}
operator auto() завезли!
http://ideone.com/sGxeQn
+3
#define __DEBUG
#ifdef __DEBUG
#define print_pair(p) do{std::cout << "(" << ((p).first + 1) << ", "\
<< ((p).second + 1) << ")" << std::endl;}while(0);
#endif
Graph::result
Graph::dijkstra (int start)
{
#ifdef __DEBUG
std::cout << "Dijkstra algorithm tracing:" << std::endl;
#endif
distances[start] = 0;
std::set<std::pair<int, int>> q;
q.insert (std::make_pair(distances[start], start));
while (!q.empty())
{
#ifdef __DEBUG
std::cout << "top element of a set: ";
print_pair(*q.begin());
#endif
int current = q.begin()->second;
q.erase(q.begin());
for (int i = 0; i < adj[current].size(); ++i)
{
#ifdef __DEBUG
std::cout << "current vertex: " << (current + 1);
std::cout << " ad current state of distances array is: " << std::endl;
for (auto i: distances)
std::cout << i << " ";
std::cout << std::endl;
#endif
int to = adj[current][i].second;
int length = adj[current][i].first;
// Relaxations
if (distances[to] > distances[current] + length)
{
#ifdef __DEBUG
std::cout << "relaxation for edge (" << current << ", " << to << ") ";
std::cout << "with weight " << length << std::endl;
#endif
q.erase(std::make_pair(distances[to], to));
distances[to] = distances[current] + length;
path[to] = current;
q.insert(std::make_pair(distances[to], to));
}
}
}
// Replace INF by -1
std::replace (distances.begin(), distances.end(), INF, -1);
return distances;
}
Я у мамы решил подебажить как мыщъх дебажил при помощи отладочной печати. Вот что получилось.
+2
#define CREATE_EVENT_LISTENER(_elname, arg1_type, arg1_name) \
class _elname : public EventListener \
{ \
private: \
class IContainer \
{ \
public: \
virtual void Call(arg1_type arg1_name) = 0; \
virtual ~IContainer() {} \
}; \
\
class FunctionContainer : public IContainer \
{ \
private: \
typedef void(*__CallbackPtr)(arg1_type); \
public: \
FunctionContainer(__CallbackPtr fn) \
{ \
this->fn = fn; \
} \
\
virtual void Call(arg1_type arg1_name) \
{ \
fn(arg1_name); \
} \
\
private: \
__CallbackPtr fn; \
}; \
\
template<class T, class Q> \
class MethodContainer : public IContainer \
{ \
public: \
MethodContainer(T method, Q _this) \
{ \
this->method = method; \
this->_this = _this; \
} \
\
virtual void Call(arg1_type arg1_name ) \
{ \
(_this->*method)(arg1_name); \
} \
\
private: \
T method; \
Q _this; \
}; \
public: \
typedef void(*__FN_CALLBACK)(arg1_type); \
\
_elname(__FN_CALLBACK fn) \
{ \
this->container = new FunctionContainer(fn); \
} \
\
template <class T, class Q> \
_elname(T method, Q _this) \
{ \
this->container = new MethodContainer<T, Q>(method, _this); \
} \
\
void Call(arg1_type arg1_name) \
{ \
container->Call(arg1_name); \
} \
\
virtual ~_elname() \
{ \
delete this->container; \
} \
private: \
IContainer* container; \
}; \
#define CREATE_EVENT(_ename, _elname, arg1_type, arg1_name) \
class _ename : public Event \
{ \
public: \
void AddListener(_elname* listener) \
{ \
Event::AddListener(listener); \
} \
\
void Handle(arg1_type arg1_name) \
{ \
for (size_t i = 0; i < this->listeners.size(); i++) \
{ \
((_elname*)listeners[i])->Call(arg1_name); \
} \
} \
\
void RemoveListener(_elname* listener) \
{ \
Event::RemoveListener(listener); \
} \
\
}; \
Я когда то это написал. Думал, это хорошая идея...
Полный файл: https://github.com/arhyme/CPP_EVENTS/blob/master/Event.h
+5
void add( std::string *str, std::string *addstr)
{
if(!strlen(addstr->c_str()))
return;
int len = strlen(str->c_str());
if( len )
{
if((str->c_str())[len-1] != ';')
*str = *str + ";";
*str = *str + *addstr;
}
else
*str = *addstr;
len = strlen(str->c_str());
if((str->c_str())[len-1] == ';')
*str = str->substr(0,len-1);
}
+3
#include <iostream>
#include <vector>
using namespace std;
int main() {
victor<bull> v = {1,0,1};
for(auto&& i : v) //Если удалить один &, то не скомпилируется
cout<<i<<endl;
return 0;
}
http://rextester.com/DBCM68277
0
SoftwareCommon::params::IParamLoader::TypeDb SettingsProxy::getTypeDb() const
{
try
{
auto type = Locator::Services::Locator->Resolve<ISettings^>()->Type;
switch (type)
{
case decltype(type)::Firebird: return IParamLoader::Firebird;
case decltype(type)::MSSQL: return IParamLoader::MSSQL;
default:
throw std::runtime_error("Unsupported db type");
}
}
catch (Exception ^ex)
{
throw std::runtime_error(marshal_1251(ex->ToString()));
}
}
+2
// p2.cpp : Defines the entry point for the console application.
// Язык Visual C++ 7.0
// Консольное приложение
// 13.07.2016
#include "stdafx.h"
#include <conio.h>
int aa (int, int, int);
void ab (int);
int _tmain(int argc, _TCHAR* argv[])
{
int a, b, c, d, e;
int f;
for (a = 0; a < 4; a++)
for (b = 0; b < 4; b++)
for (c = 0; c < 4; c++)
for (d = 0; d < 4; d++)
for (e = 0; e < 4; e++)
{
f = aa (1, a, 2);
f = aa (f, b, 3);
f = aa (f, c, 4);
f = aa (f, d, 5);
f = aa (f, e, 6);
if (f == 35)
{
printf ("((((1 "); ab (a);
printf ("2) "); ab (b);
printf ("3) "); ab (c);
printf ("4) "); ab (d);
printf ("5) "); ab (e);
printf ("6 = 35.\n");
}
}
getch ();
return 0;
}
int aa (int a, int b, int c)
{
switch (b)
{
case 0: return a + c;
case 1: return a - c;
case 2: return a * c;
case 3: return a / c;
}
return 0;
}
void ab (int a)
{
switch (a)
{
case 0: printf ("+ "); break;
case 1: printf ("- "); break;
case 2: printf ("* "); break;
case 3: printf ("/ "); break;
}
}
Задача: В написанном выражении ((((1 ? 2) ? 3) ? 4) ? 5) ? 6 вместо каждого знака ? вставить знак одного из четырёх арифметических действий: +, -, *, / так, чтобы результат вычислений равнялся 35.
+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;
}