- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
std::vector <CElement> elemGun
std::vector <CElement> eOther
...
elemGun[0].wVx/=2.f;
elemGun[0].wVy/=2.f;
eOther.push_back(elemGun[0]);
elemGun[0].wVx*=2.f;
elemGun[0].wVy*=2.f;
...
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+165
std::vector <CElement> elemGun
std::vector <CElement> eOther
...
elemGun[0].wVx/=2.f;
elemGun[0].wVy/=2.f;
eOther.push_back(elemGun[0]);
elemGun[0].wVx*=2.f;
elemGun[0].wVy*=2.f;
...
+169
bool NSFileExists(const char * FileName)
{
struct _stat fStats;
return (_stat(FileName, &fStats) == 0);
}
#if 0
bool NSFileExists(const char * FileName)
{
WIN32_FIND_DATA fd;
HANDLE hFF;
bool bExist(true);
hFF = FindFirstFile(FileName, &fd);
if (hFF == INVALID_HANDLE_VALUE) bExist = false;
else FindClose(hFF);
return bExist;
}
#endif
#if 0
bool NSFileExists(const char * FileName)
{
HANDLE hFile = ::CreateFile(FileName, 0, 0, 0, OPEN_EXISTING, 0, 0);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
return true;
}
return false;
}
#endif
Эволюция!
Без комментариев...
+157
// ...
ReplaceHtmlEntities( std::string(abstract), true );
// ...
В одном из проектов было найдено (очередная операция подергивания):
void ReplaceHtmlEntities(std::string &, bool /* = true */);
abstract - const char *
+170
int GetRndWithRnd(int iRnd, int iRndPlusMinus)
{
if(!iRndPlusMinus) return iRnd;
switch((Rand())%2)
{
case 1:
// plus
return (int)(iRnd+(Rand()%iRndPlusMinus));
break;
default:
// minus
return (int)(iRnd-(Rand()%iRndPlusMinus));
break;
}
return 0;
}
Чтоб враги не догадались
+166
TagsTree ParseXML(const char file_name[])
{
ifstream input_file(file_name, std::ios::in);
string content;
if(!input_file.good())
{
throw "can't open xml";
}
while(!input_file.eof())
{
char buffer[256];
input_file.read(buffer, 256);
streamsize read_count = input_file.gcount();
content.append(buffer, buffer+read_count);
}
input_file.close();
auto Cleanup = [&content](const string& what_to_del) -> void
{
string::size_type pos = content.find(what_to_del);
while(pos != string::npos)
{
content.erase(pos, what_to_del.size());
pos = content.find(what_to_del, pos);
}
};
Cleanup("\n");
Cleanup("\t");
Cleanup(" ");
string::size_type comment_begin = 0;
string::size_type comment_end = 0;
for(;;)
{
string::size_type comment_begin = content.find("<!--", comment_end);
if(comment_begin == string::npos)
{
break;
}
string::size_type comment_end = content.find(">", comment_begin+3);
if(comment_end == string::npos)
{
throw "invalid xml: no comment closing brace";
}
content.erase(comment_begin, comment_end-comment_begin+1);
comment_end = comment_begin;
}
string::size_type header_begin = content.find("<?xml");
if(header_begin == string::npos)
{
throw "invalid xml: no header";
}
string::size_type header_end = content.find(">", header_begin+4);
if(header_end == string::npos)
{
throw "invalid xml: no header closing brace";
}
content.erase(comment_begin, header_end-header_begin+1);
auto CutTagAndContent = [](string& from, string& tag, string& content) -> void
{
string::size_type position = from.find('>');
if(position == string::npos)
{
throw "invalid xml: no tag closing brace";
}
tag = from.substr(1, position-1);
position = from.find("</"+tag+'>', position);
if(position == string::npos)
{
throw "invalid xml: no closing tag";
}
content = from.substr(tag.size()+2, position-tag.size()-2);
from.erase(0, position+tag.size()+3);
};
if(content[0] != '<')
{
throw "invalid xml: to root tag";
}
TagsTree result;
CutTagAndContent(content, result.Node.name, result.Node.content);
TagsTree::children_vectorT children;
children.push_back(&result);
do
{
for(auto i = children.begin(); i!= children.end(); i++)
{
while(!(**i).Node.content.empty())
{
if((**i).Node.content[0]!='<')
{
break;
}
TAG temporary;
CutTagAndContent((**i).Node.content, temporary.name, temporary.content);
(**i).Push(temporary);
}
}
children = EnlistChildren(children);
}
while(!children.empty());
return result;
}
Говнонедопарсер недоговноXML. Дерево тэгов - отдельная кучка.
+166
template <typename RetT> RetT Max() { return (RetT)0; }
template <typename RetT, typename ArgT, typename ... Args> RetT Max(ArgT Arg1, Args ... args)
{ RetT Temp = Max<RetT>(args ...); return ((RetT)Arg1 > Temp) ? ((RetT)Arg1) : (Temp); }
int main(int argc, char* argv[])
{
printf("%d\n", Max<int>(100, 200.356, false, -300));
return 0;
}
оцените полет человеческой мысли и чудеса нового стандарта С++0x... семпл мой, правда довольно редко используется...
+167
int pm = pm == -2 ? -1 : pm_ == -1 ? mi : pm_;
Фрагмент из функции поиска, определение какого-то индекса.
+163
int F(x)
{
if (.chto-to) v.push_back(.koe-chto.);
int ind = somefunc(x);
for each y in x.childs
v[ind].res += F(y);
}
Не говнокод, но пример того, как из std::vector можно выстрелить себе в ногу
Комментарий автора кода ( http://codeforces.ru/blog/entry/1719#comment-32824 ):
такая штука получала крэш на компиляторе жюри, из-за того что сначала вычислялся адрес v[ind].res затем вызывалась снова F, которая пушбекает в вектор v, и может тем самым заставить вектор перевыделить память, тем самым адрес вычисленный ранее становился инвалидным.
я этот баг долго не мог найти, потомучто студия генерила нормальный код, не вызывающий креша
+167
#include <windows.h>
struct io
{
io()
{
SetConsoleTitle(__FUNCSIG__);
}
~io()
{
DebugBreak();
}
} io_obj;
int main()
{
}
typedef void(fn_t)();
#pragma comment(linker, "/merge:.CRT=.rdata")
#pragma data_seg(".CRT$XCA")
extern "C" fn_t * start[] = {0};
#pragma data_seg(".CRT$XCZ")
extern "C" fn_t * finish[] = {0};
#pragma data_seg()
void call_dtors();
extern "C" void _initterm()
{
fn_t **p = start, **q = finish;
while (p < q)
{
if (*p)
(*p)();
++p;
}
main();
call_dtors();
}
fn_t * dtors[999];
int c_dtors;
void call_dtors()
{
while (c_dtors--)
dtors[c_dtors]();
}
extern "C" int atexit(void (__cdecl *func )( void ))
{
dtors[c_dtors++] = func;
return !"unspecified";
}
если клепаем что то без CRT и хотим чтоб вызывались
конструкторы деструкторы статических объектов и хотим свое то
вот реализация для тех кто этого еще неделал
https://wasm.ru/forum/viewtopic.php?pid=428250#p428250
+165
//
// Занимательное программирование C++
// С.Симонович, Г.Евсеев, 2001
//
// Глава 12. Программа учится сочинять
//
void __fastcall TForm1::FormCreate
(TObject *Sender)
{
randomize();
ComboBox1->ItemIndex = 0;
ComboBox2->ItemIndex = 0;
ComboBox3->ItemIndex = 0;
}
void __fastcall TForm1::Button1Click
(TObject *Sender)
{
ComboBox1->ItemIndex =
random(ComboBox1->Items->Count);
ComboBox2->ItemIndex =
random(ComboBox2->Items->Count);
ComboBox3->ItemIndex =
random(ComboBox3->Items->Count);
}
Это моя первая книгка по Си++
печалько... тт