- 1
- 2
const
#include "file.xpm"
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+8
const
#include "file.xpm"
У чувака в файле file.xpm объявлен массив static char * icon_xpm [] = { "..", "..", ... } и он не может заинклудить его в плюсовый код. Вот такой воркараунд ему предложили.
https://www.linux.org.ru/forum/development/10400992?cid=10406949
+3
#include <iostream>
class A
{
public:
virtual void print(int val = 10) { std::cout << "A" << val; }
};
class B : public A
{
public:
virtual void print(int val = 20) { std::cout << "B" << val; }
};
int main()
{
B b;
A& a = b;
a.print();
return 0;
}
when you see it, you’ll shit bricks
0
// check that all selected vertices are one 3d vertex.
bool UsedIndex = 0;
bool IndexIsRegistered = false;
for (int t = 0; t < Indices.count(); t++)
{
zUVVertex Vertex = OldVerts->at(t);
if (!IndexIsRegistered)
{
IndexIsRegistered = true;
UsedIndex = Vertex.BaseVertexIndex;
}
else if (UsedIndex != OldVerts->at(t).BaseVertexIndex)
{
// quit on fail
return;
}
}
NewList = new QList<zUVVertex>();
zUVVertex NewVertex;
bool VertexIsInitialized = false;
bool CapIsHoled = false;
for (quint32 t = 0; t < OldVerts->count(); t++)
{
bool Taked = false;
for (quint32 j = 0; j < Indices.count(); j++)
{
if (OldVerts->at(t).index == Indices.at(j))
{
if (!VertexIsInitialized)
{
VertexIsInitialized = true;
NewVertex = OldVerts->at(t);
}
Taked = true;
NewVertex.IndicesBeforeWeld << t;
break;
}
}
if (!Taked)
{
(*NewList) << OldVerts->at(t);
}
else
{
zUVVertex Stub;
if (!CapIsHoled)
{
Stub = NewVertex;
}
else
{
Stub.Index = 0x7FFFFFFF;
}
(*NewList) << Stub;
}
}
(*NewList) << NewVertex;
Taked = false;
QList<zUVFace> *TempFacesList = new QList<zUVFace>();
for (int t = 0; t < Faces->count(); t++)
{
zUVFace Face = Faces->at(t);
zUVFace NewFace;
for (int j = 0; j < Face.VertsIndices; j++)
{
quint32 Index0 = Face.VertsIndices.at(j);
zUVVertex TestVertex = NewList->at(Index0);
if (TestVertex.Index == 0x7FFFFFFF)
{
// need to replace
NewFace = Faces->at(t);
NewFace.VertsIndices.operator [](j) = NewList->count() - 1;
Taked = true;
}
}
if (Taked)
{
(*TempFacesList) << NewFace;
}
}
http://www.gamedev.ru/code/forum/?id=216701
+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);
}