- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
#include <iostream>
using namespace std;
struct Foo {char a; int b; char c;};
struct Bar {char a; char b; int c;};
int main() {
cout << sizeof(Foo) << endl;
cout << sizeof(Bar) << endl;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
#include <iostream>
using namespace std;
struct Foo {char a; int b; char c;};
struct Bar {char a; char b; int c;};
int main() {
cout << sizeof(Foo) << endl;
cout << sizeof(Bar) << endl;
}
https://ideone.com/XKWey3
Какой бароп )))
0
Node* reverse(Node* head)
{
Node *end = head, *current = head;
while (end->next != nullptr) {
end = end->next;
}
Node *initial_end = end, *temp = nullptr, *temp_2 = nullptr;
end->next = current;
temp = current;
current = current->next;
temp->next = nullptr;
while (current != initial_end) {
temp_2 = initial_end->next;
initial_end->next = current;
temp = current;
current = current->next;
temp->next = temp_2;
}
return initial_end;
}
Я где-то прочитал, что на собесе нужно написать переворот односвязного списка за 5 минут... Спустя 2 дня получилось это.
0
class std::unordered_map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,
enum REG,struct std::hash<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,
struct std::equal_to<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,
class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,
class std::allocator<char> > const ,enum REG> > > registers"
(?registers@@3V?$unordered_map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@W4REG@@U?$hash@V?$
basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@U?$equal_to@V?$basic_string@DU?$char_traits@D@std@@V?
$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@W4
REG@@@std@@@2@@std@@A) уже определен в decoder.obj PVC-16 C:\Users\Люда\source\repos\PVC-16\PVC-16\interrupt.obj 1
Похлопаем visual c++ за понятный лог.
0
#include <cstdlib>
#include <chrono>
#include <iostream>
#include <thread>
int p = 0;
int *q = nullptr;
void g()
{
using namespace std::chrono_literals;
std::cout << "g()" << std::endl;
std::cout << "g(): p = 1" << std::endl;
p = 1;
std::this_thread::sleep_for(1s);
if (q != nullptr) {
std::cout << "g(): *q = 1" << std::endl;
*q = 1;
} else {
std::cout << "g(): q == nullptr" << std::endl;
}
}
void f()
{
using namespace std::chrono_literals;
std::cout << "f()" << std::endl;
if (p == 0) {
std::cout << "f(): first loop start" << std::endl;
while (p == 0) { } // Потенциально конечный
std::cout << "f(): first loop end" << std::endl;
}
int i = 0;
q = &i;
std::cout << "f(): second loop start" << std::endl;
while (i == 0) { } // Потенциально конечный, хотя в условии только автоматическая пельменная
std::cout << "f(): second loop end" << std::endl;
}
int main()
{
using namespace std::chrono_literals;
std::cout << "f() thread start" << std::endl;
auto thr1 = std::thread(f);
thr1.detach();
std::this_thread::sleep_for(1s);
std::cout << "g() thread start" << std::endl;
auto thr2 = std::thread(g);
thr2.detach();
std::this_thread::sleep_for(2s);
std::cout << "Done" << std::endl;
std::_Exit(EXIT_SUCCESS);
}
Ожидание:
f() thread start
f()
f(): first loop start
g() thread start
g()
g(): p = 1
f(): first loop end
f(): second loop start
g(): *q = 1
f(): second loop end
Done
0
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>
const int x_size(20), y_size(10); int x_pos(x_size/2+1); int y_pos(y_size/2+1);
enum border_types{lineNL, single, singleNL};
enum directions{UpLeft=1, UpRight, DownLeft, DownRight}dir;
void draw_border(enum border_types borders) {
do{
if(borders == single || borders == singleNL) break;
for(int i=0; i<x_size+1; i++)
putchar('#');
}while(false);
putchar('#');
if(borders == singleNL || borders == lineNL) std::cout << '\n';}
void display_update() {
system("cls");
draw_border(lineNL);
for(int i=1; i<=y_size; i++)
{
draw_border(single);
for(int j=1; j<=x_size; j++)
{
if(j == x_pos && i == y_pos)
{
putchar('x');
continue;
}
putchar(32);
}
draw_border(singleNL);;
}
draw_border(lineNL);
std::cout << "X: " << x_pos << "\tY: " << y_pos;}
void logic() {
switch(x_pos)
{
case 1:
if(dir == UpLeft) dir = UpRight;
if(dir == DownLeft) dir = DownRight;
break;
case x_size:
if(dir == UpRight) dir = UpLeft;
if(dir == DownRight) dir = DownLeft;
}
switch(y_pos)
{
case 1:
if(dir == UpLeft) dir = DownLeft;
if(dir == UpRight) dir = DownRight;
break;
case y_size:
if(dir == DownLeft) dir = UpLeft;
if(dir == DownRight) dir = UpRight;
}}
void move() {
switch(dir)
{
case UpLeft:
x_pos--;
y_pos--;
break;
case UpRight:
x_pos++;
y_pos--;
break;
case DownLeft:
x_pos--;
y_pos++;
break;
case DownRight:
x_pos++;
y_pos++;
}}
int main() {
srand(time(0));
rand();
switch(rand()%4+1)
{
case UpLeft:
dir = UpLeft;
break;
case UpRight:
dir = UpRight;
break;
case DownLeft:
dir = DownLeft;
break;
case DownRight:
dir = DownRight;
}
while(!kbhit())
{
display_update();
logic();
move();
}
return 0;}
Сорян, пришлось уплотнить фигурные скобки, чтобы код уместился в 100 строк.
0
class UnitedFigure : public Figure {
Figure &f1;
Figure &f2;
public:
UnitedFigure (Figure &_f1, Figure &_f2) : f1(_f1), f2(_f2) {}
double distance_to(const Point &p) const override {
return std::min(f1.distance_to(p), f2.distance_to(p));
}
}
Завезли ссылочные поля класса, это в каком стандарте?
Даже тестил когда то такое, наверное на C++03 и получал ошибку компилятора.
Я и не знал, что добавили такую прекрасную возможность выстрелить себе в ногу.
0
uint64_t stored_msg_id = _container_msg_id.get(ctrl_msg.sequence); // Получаем msg_id из мапы для связки сообщений
if (stored_msg_id)
proto_fill(ctrl_msg, stored_msg_id); // если он там был то новому сообщению даем этот msg_id
else
proto_fill(ctrl_msg); // Иначе формируем новый msg_id
// Отсылаем сообщение
...
// Если msg_id не был в _container_msg_id то произойдет попытка вставки msg_id полученного через proto_fill.
if (!stored_msg_id && !_container_msg_id.insert(ctrl_msg.sequence, ctrl_msg.msg_id))
{
DEBUG(L, 0, "[%p] Can't store request's control message id (%llu) in bunch map" \
", response's msg_id will differ", this, msg.msg_id);
}
С точки зрения читабельности кода, в последнем ветвлении говнокод?
+1
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
https://github.com/greatis/Anti-WebMiner/blob/master/AntiWebMiner.cpp#L23
+3
foreach ($files as $n => $f) {
$new_content = $common.$namespace_begin.$f.$namespace_end;
$std_methods = array();
preg_match_all('/std::[a-z_0-9]*/', $new_content, $std_methods);
$std_methods = array_unique($std_methods[0]);
$needed_std_headers = array();
$type_headers = array(
'std::move' => '',
'std::vector' => '',
'std::string' => '',
// [...]
'std::unordered_set' => 'unordered_set');
foreach ($type_headers as $type => $header) {
if (in_array($type, $std_methods)) {
$std_methods = array_diff($std_methods, array($type));
if ($header && !in_array($header, $needed_std_headers)) {
$needed_std_headers[] = $header;
}
}
}
if (!$std_methods) { // know all needed std headers
$new_content = preg_replace_callback(
'/#include <([a-z_]*)>/',
function ($matches) use ($needed_std_headers) {
if (in_array($matches[1], $needed_std_headers)) {
return $matches[0];
}
return '';
},
$new_content
);
}
Тут вот в https://govnokod.ru/20049 CHayT предлагал использовать «PHP» в качестве препроцессора для «C» — так вот в «Телеграме» совет оценили и решили взять на вооружение.
https://github.com/tdlib/td/blob/master/SplitSource.php
+1
#include <vector>
#include <cwchar>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<const wchar_t*> leaders{L"Ленин", L"Сталин", L"Маленков",
L"Хрущёв", L"Брежнев", L"Андропов", L"Черненко", L"Горбачёв"};
std::sort(leaders.begin(), leaders.end(), [](auto strA, auto strB) {
return std::wcscmp(strA, strB) < 0;
});
std::setlocale(LC_ALL, "en_US.utf8");
std::wcout.imbue(std::locale("en_US.utf8"));
for (auto leader : leaders)
std::wcout << leader << '\n';
}
Отсюда:
https://en.cppreference.com/w/cpp/string/wide/wcscmp