- 1
- 2
- 3
- 4
- 5
- 6
#include <windows.h>
int main() {
HDC dc = CreateCompatibleDC (NULL);
SetLayout (dc, LAYOUT_RTL);
ScaleWindowExtEx (dc, -2147483647 - 1, -1, 1, 1, NULL);
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+3
#include <windows.h>
int main() {
HDC dc = CreateCompatibleDC (NULL);
SetLayout (dc, LAYOUT_RTL);
ScaleWindowExtEx (dc, -2147483647 - 1, -1, 1, 1, NULL);
}
bsod
+4
void delslovo(char *a)
{
static int i = 0;
static bool j = false;
if (a[i++] != '\0') delslovo(a);
else i--;
if (!j)
{
if (a[i] != ' '&&a[i] != '\n'&&a[i] != '\0')
{
j = true;
i++;
}
}
if (j)
{
if (a[i - 1] == ' ') return;
a[i - 1] = a[i];
}
i--;
}
вот так надо удалять последнее слово из строки
+4
#include <IO/Stream.h>
#include "Algorithms/Range.h"
#include "Algorithms/RangeConstruct.h"
#include "Algorithms/RangeIteration.h"
#include "Algorithms/RangeMutation.h"
using namespace IO;
using namespace Range;
int main()
{
Console.PrintLine("Есть нормальная поддержка Юникода в консоли, даже на винде.");
Console.PrintLine("Тестируется текст с кириллицей, греческим алфавитом αβγδεζηθικλμνξο, а также с иероглифами ㈇㌤㈳㌛㉨.");
Console.PrintLine("Иероглифы не отображаются в консоли, потому что консольный шрифт их не содержит, но копируются оттуда нормально.");
StringView strs[] = {"hello", "world"};
StringView strs1[] = {"range", "testing", "program"};
StringView strs2[] = {"C++", "крут"};
Console.PrintLine("В тесте используются три массива:", endl, strs, endl, strs1, endl, strs2);
Console.PrintLine(endl, "Пример вывода initializer list:", endl, AsRange<double>({4353.435, 3243.23, 21.421, 12355.5, 64532}));
auto fib = Recurrence(Algo::Op::Add<int>, 1, 1);
Array<int> fibArr;
fibArr.SetCountUninitialized(15);
auto copyResult = fib.Take(15).Copy(fibArr());
Console.PrintLine(endl, "Последовательность Фибоначчи в массиве: ", endl, fibArr());
Console.PrintLine(endl, "Вторая половина того же массива задом наперёд: ", endl, fibArr($/2, $).Retro());
fib.Drop(5).Take(15).Copy(fibArr.Insert($));
Console.PrintLine(endl, "Добавляем 15 чисел Фибоначчи, начиная с пятого, в конец. Новое содержимое массива: ");
Console.PrintLine(fibArr());
Console.PrintLine(endl, "Объединяем элементы различных диапазонов в диапазоне кортежей: ", endl, ToString(
Zip(
fib.Take(30),
Chain(AsRange(strs), AsRange(strs1), AsRange(strs2)).Cycle().Take(20),
Recurrence([](int a, int b){return a*2+b;}, 1, 1).Take(17).Cycle().Drop(3).Take(22),
fib.Take(19).Cycle().Drop(5).Take(50).Stride(3),
Recurrence(Algo::Op::Mul<ulong64>, 2ull, 3ull).Take(9)
),
",\n ", "[\n ", "\n]"));
static const StringView pattern[] = {"pattern", "fills", "range"};
Chain(AsRange(strs), AsRange(strs1), AsRange(strs2)).FillPattern(AsRange(pattern));
Console.PrintLine(endl, "Поменяли сразу три массива одним вызовом FillPattern: ");
Console.PrintLine(strs, endl, strs1, endl, strs2, endl);
Console.PrintLine("11-й элемент зацикленного массива строк: ", endl, AsRange(strs).Cycle().Take(11).Tail(1), endl);
Console.PrintLine("Перевёрнутый массив строк: ", endl, AsRange(strs).Retro(), endl);
Console.PrintLine("Зациклили первые два элемента массива и взяли 10 из них:");
Console.PrintLine(AsRange(strs1).Take(2).Cycle().Take(10) );
Console.PrintLine("Между массивом строк и 5 числами Фибоначчи выбрали второе в рантайме: ");
Console.PrintLine(Choose(AsRange(strs1), fib.Take(5).Map([](int x){return ToString(x);}), true) );
static const size_t indices[] = {1,1,1,2,2,0,2,1,0};
Console.PrintLine(
RoundRobin(
AsRange(strs1).Indexed(AsRange(indices)),
Repeat(StringView("Test"), 5),
AsRange(strs1),
AsRange(strs2)
));
Console.PrintLine(endl, "Введите строки, которые войдут в диапазон строк. В конце введите \"end\".");
Console.PrintLine("Вы ввели следующие строки:", endl, ToString(Console.ByLine("end")) );
int arr[]={1, 4, 11, 6, 8};
Console.PrintLine("max{1, 4, 11, 6, 8} = ", AsRange(arr).Reduce(Algo::Op::Max<int>));
Console.PrintLine("Генерация 100 случайных чисел от 0 до 999 и вывод квадратов тех из них, которые делятся на 7: ", endl,
Generate([](){return math::urandom()%1000;}).Take(100)
.Filter([](uint x) {return x%7==0;})
.Map(math::sqr<uint>)
);
return 0;
}
Давно здесь не было моих велосипедов. А они с тех пор сильно эволюционировали, я даже многие фичи из языка D смог перенести в C++.
Вывод в консоль и обсуждение здесь: http://www.gamedev.ru/flame/forum/?id=216045&page=99#m1481
+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.