- 1
- 2
- 3
- 4
- 5
- 6
ostringstream s;
...
- return s.str();
+ return std::move(s.str());
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+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;
}
0
switch (count)
{
case 1:
cout << okonch1 << endl;
if (okonch1 == okonchanie1)
{
cout << slovo_okonch1_1 << endl;
}
else
{
if (okonch1 == okonchanie2)
{
cout << slovo_okonch2_1 << endl;;
}
else
{
if (okonch1 == okonchanie3)
{
cout << slovo_okonch3_1 << endl;;
}
else
{
if (okonch1 == okonchanie4)
{
cout << slovo_okonch4_1 << endl;
}
else
{
if (okonch1 == okonchanie5)
{
cout << slovo_okonch5_1 << endl;
}
else
{
if (okonch1 == okonchanie6)
{
cout << slovo_okonch6_1 << endl;
}
else
{
if (okonch1 == okonchanie7)
{
cout << slovo_okonch7_1 << endl;
}
else
{
if (okonch1 == okonchanie8)
{
cout << slovo_okonch8_1 << endl;
}
}
}
}
}
}
}
}
Создана куча переменных okonch*_* и по ним происходит switch
Что самое смешное(или ужасное?) - этого кода на 500 строк...
−1
AnsiString message=IntToStr((int)GetTickCount());
if(message.Length()>=3)
message=message.SubString(message.Length()-3, 3);
else if(message.Length()==2)
message="0"+message;
else if(message.Length()==1)
message="00"+message;
message=dt.FormatString("yy")+dt.FormatString("mm")+dt.FormatString("dd")+" "+
dt.FormatString("hh")+dt.FormatString("nn")+dt.FormatString("ss")+" "+message;
message=message+" "+aMessage;
if(FMemoMes){
FMemoMes->Lines->Add(message);
}
Выводит сообщение aMessage, вставляя в начало сообщения текущие дату и время с миллисекундами.
−1
GUIButton::GUIButton(ResourceManager& resourceManager, const Renderer& renderer,
const Config& config, std::string name, Action action,
int x, int y, int width, int height) :
GUIButton{std::move(name), std::move(action),
resourceManager.load<Font>("font_button_" + name,
config.findValue<std::string>("button", "font"),
config.findValue<int>("button", "font_size")),
resourceManager.load<TextureAtlas>("atlas_button", resourceManager, renderer,
Config{config.findValue<std::string>("button", "atlas_config")}), x, y, width, height}
{
}
+2
https://m.reddit.com/r/cpp/comments/4pmlpz/what_the_iso_c_committee_added_to_the_c17_working/
Мне остаётся только спросить:
+3
void MyZKbMain::keyPressEvent(QKeyEvent* k)
{
QPixmap pm; pm.load("ruleta_usr.png");
ZConfig Num(QString("numeros.cfg"), true);
ZConfig Hist(QString("historial.cfg"), true);
switch (k->key())
{
case 0x1046: //Boton Verde
break;
case 0x1030: //Boton Verde
calcular=0;
reboot = new ZMessageDlg("zRoulette",
QString("Sistema Ubeda 0.5\nBasado en el Sistema de Cuadros\n\nwww.developermoto.com/es\nwww.modmymoto.com\n\n(C)2009 RacingLocura07, CepiPerez"),
(ZMessageDlg::MessageDlgType)2, 0, this,"about", true, 0);
reboot->setTitleIcon(pm); reboot->show();
break;
case 0x1031: //Boton Rojo
calcular=0;
reboot = new ZMessageDlg("zRoulette", "Desea salir?",
(ZMessageDlg::MessageDlgType)1, 0, this,"about", true, 0);
reboot->setTitleIcon(pm); reboot->show();
if(reboot->exec()==1) { exit(); }
else { update(); break; }
case 0x1012: //Tecla de Navegacion De Izquierda
calcular=0;
if (current > 1 ) { --current; update(); break; } else { break; }
case 0x1013: //Tecla de Navegacion De Arriba
calcular=0;
if ( current > 3 ) { ------current; update(); break; } else { break; }
case 0x1014: //Tecla de Navegacion De Derecha
calcular=0;
if (current < 36 ) { ++current; update(); break; } else { break; }
case 0x1015: //Tecla de Navegacion De Abajo
calcular=0;
if (current < 34 ) { ++++++current; update(); break; } else { break; }
case 0x1038: //Softkey Izquierda
calcular=0;
reboot = new ZMessageDlg("zRoulette", "Desea reinciar la Ruleta?", (ZMessageDlg::MessageDlgType)1, 0, this,"about", true, 0);
reboot->setTitleIcon(pm); reboot->show();
if(reboot->exec()==1) { system("rm numeros.cfg"); system("rm historial.cfg"); current = 1; jugadas = 0; lista.clear(); update(); break; }
else { update(); break; }
case 0x103a: //Softkey Derecha
int temp = Hist.readNumEntry ( QString("HISTORIAL"), QString("18"), 0 );
if ( temp != 0 ) {
reboot = new ZMessageDlg("zRoulette", "Desea limpiar las jugadas dejando las ultimas 18 solamente?",
(ZMessageDlg::MessageDlgType)1, 0, this,"about", true, 0); reboot->setTitleIcon(pm); reboot->show();
if(reboot->exec()==1) {
for ( int l=1; l<37; ++l) { Num.writeEntry ( QString("NUMEROS"), QString("%1").arg(l), QString("0") ); }
for ( int j=1; j<19; ++j) {
int temp = Hist.readNumEntry ( QString("HISTORIAL"), QString("%1").arg(j), 0 );
if ( temp > 0 ) { Num.writeEntry ( QString("NUMEROS"), QString("%1").arg(temp), QString("1") ); }
} calcular=1; update(); break;
} else { break; }
} else {
reboot = new ZMessageDlg("zRoulette", "Deben haber mas de 18 bolas jugadas para el reinicio parcial.",
(ZMessageDlg::MessageDlgType)2, 0, this,"about", true, 0); reboot->setTitleIcon(pm); reboot->show(); break;
}
case 0x1004: //Boton Central
valortemp = Num.readNumEntry(QString("NUMEROS"), QString("%1").arg(current), 0 );
if ( valortemp < 1 ) { valortemp=0; } ++valortemp;
Num.writeEntry(QString("NUMEROS"), QString("%1").arg(current), valortemp);
int lugar=0; for ( int j=18; j>0; --j)
{ int temp = Hist.readNumEntry ( QString("HISTORIAL"), QString("%1").arg(j), 0 ); if ( temp==0 ) { lugar=j; } }
if ( lugar > 0 ) {
Hist.writeEntry ( QString("HISTORIAL"), QString("%1").arg(lugar), QString("%1").arg(current) );
} else {
for ( int j=1; j<18; ++j) {
int temp = Hist.readNumEntry ( QString("HISTORIAL"), QString("%1").arg(j+1), 0 );
Hist.writeEntry ( QString("HISTORIAL"), QString("%1").arg(j), QString("%1").arg(temp) );
}
Hist.writeEntry ( QString("HISTORIAL"), QString("18"), QString("%1").arg(current) );
}
calcular=1;
update();
}
}
Разработчики из солнечной Аргентины. Кусочек кода из кастомного "лаунчера" для телефонов Motorola на платформе MotoMAGX (Linux 2.6.10, Qt 2.3.8, gcc 3.4.3). АДИЩЕ С ЦАРСКИМИ АНРОЛЛАМИ: https://github.com/crutchwalkfactory/motocakerteam/blob/master/Projects/MotoDesk/MyZKbMain.cpp
Что интересно, это всё как-то работало и даже довольно мило выглядело: http://exlmoto.ru/wp-content/Images/AOne/1.gif
+3
#include "stdafx.h"
#include <Windows.h>
#pragma comment(lib, "gdiplus.lib")
#include <gdiplus.h>
#include <vector>
#include <chrono>
wchar_t* path =
L"здесь был путь*";
using namespace Gdiplus;
using namespace std::chrono;
int main()
{
GdiplusStartupInput gdipInput;
ULONG_PTR gdipToken;
GdiplusStartup(&gdipToken, &gdipInput, NULL);
HWND progman = FindWindowW(L"Progman", NULL);
HWND workerw = GetWindow(progman, GW_HWNDPREV);
HDC dc = GetDC(workerw);
std::vector<Bitmap*> images;
WIN32_FIND_DATAW fdata = { 0 };
HANDLE hFind = FindFirstFileW(path, &fdata);
int
scrWidth = GetSystemMetrics(SM_CXSCREEN),
scrHeight = GetSystemMetrics(SM_CYSCREEN);
UINT width, height;
bool isInfoRetrieved = false;
std::wstring wmp(path);
wmp = wmp.substr(0, wmp.length() - 1);
do {
Bitmap* bmp = Bitmap::FromFile((wmp + fdata.cFileName).c_str());
if (bmp->GetLastStatus() != Gdiplus::Ok) continue;
int width = bmp->GetWidth();
int height = bmp->GetHeight();
double ratio = (double)width / height;
if (ratio > 1) {
width = scrWidth;
height = scrWidth / ratio;
}
else {
width = scrHeight * ratio;
height = scrHeight;
}
Bitmap* resized = new Bitmap(width, height, PixelFormat32bppRGB);
Graphics* resizedGr = Graphics::FromImage(resized);
resizedGr->DrawImage(bmp, 0, 0, width, height);
delete resizedGr;
delete bmp;
images.push_back(resized);
} while (FindNextFile(hFind, &fdata));
FindClose(hFind);
Graphics* mainGr = Graphics::FromHDC(dc);
Bitmap* bufBmp = new Bitmap(scrWidth, scrHeight, PixelFormat32bppRGB);
Graphics* bufGr = Graphics::FromImage(bufBmp);
int count = images.size();
int gap = 1000 / count;
while (true) {
for (auto it = images.begin(); it != images.end(); it++) {
milliseconds ms1 = duration_cast<milliseconds>(
system_clock::now().time_since_epoch());
Bitmap* bmp = *it;
int width = bmp->GetWidth();
int height = bmp->GetHeight();
int xOfs = (scrWidth - width) / 2, yOfs = (scrHeight - height) / 2;
bufGr->Clear(Color::Black);
bufGr->DrawImage(*it, xOfs, yOfs, width, height);
mainGr->DrawImage(bufBmp, 0, 0);
milliseconds ms2 = duration_cast<milliseconds>(
system_clock::now().time_since_epoch());
milliseconds delta = ms2 - ms1;
if (gap > delta.count())
Sleep(gap - delta.count());
}
}
return 0;
}
Код для рисования под иконками рабочего стола на винде
Да, в винде можно так делать
Нахуй никому не нужно, но выглядит заебись
+2
const size_t longstring_size = 1000500; // TODO: O RLY magic constant? => Can't load edges >= 1Mbp
char longstring[longstring_size];
Орфография комментариев сохранена.