- 1
- 2
#define ONE_GB 1024
#define FIVE_GB 5115
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
#define ONE_GB 1024
#define FIVE_GB 5115
Написано в очень известной Калифорнийской конторе
+3
#include <set>
#include <algorithm>
bool overlap(const std::set<int>& s1, const std::set<int>& s2)
{
for( const auto& i : s1) {
if(std::binary_search(s2.begin(), s2.end(), i))
return true;
}
return false;
}
я зделял
https://stackoverflow.com/a/29421606/1683138
-- https://en.cppreference.com/w/cpp/container/set+1
class TaxStorage {
public:
using TaxCode = Code<3>; // Code<int N, typename Storage = uint32_t> тип для маленьких строк
using TaxType = Code<3>;
using TaxId = std::tuple<TaxCode, TaxType>;
using TaxMap = std::map<TaxId, int>
using CityId = int;
using TaxPointMap = std::unordered_map<CityId, TaxMap>;
TaxMap forCityOrOther(const TaxPointMap& map, const CityId cityId) const {
const auto found = map.find(cityId);
return found == map.cend() ? map.at(OTHER_CITY) : *found; // должно быть found->second
}
}
Dev: Ok GCC, tell me what is wrong.
GCC: /home/whatever/project/TaxStorage.h:102: error: incompatible operand types ('const std::unordered_map<int, std::map<std::tuple<Code<3, unsigned int>, Code<3, unsigned int> >, std::vector<unsigned long, std::allocator<unsigned long> >, std::less<std::tuple<Code<3, unsigned int>, Code<3, unsigned int> > >, std::allocator<std::pair<const std::tuple<Code<3, unsigned int>, Code<3, unsigned int> >, std::vector<unsigned long, std::allocator<unsigned long> > > > >, std::hash<int>, std::equal_to<int>, std::allocator<std::pair<const int, std::map<std::tuple<Code<3, unsigned int>, Code<3, unsigned int> >, std::vector<unsigned long, std::allocator<unsigned long> >, std::less<std::tuple<Code<3, unsigned int>, Code<3, unsigned int> > >, std::allocator<std::pair<const std::tuple<Code<3, unsigned int>, Code<3, unsigned int> >, std::vector<unsigned long, std::allocator<unsigned long> > > > > > > >::mapped_type' (aka 'const std::map<std::tuple<Code<3, unsigned int>, Code<3, unsigned int> >, std::vector<unsigned long, std::allocator<unsigned long> >, std::less<std::tuple<Code<3, unsigned int>, Code<3, unsigned int> > >, std::allocator<std::pair<const std::tuple<Code<3, unsigned int>, Code<3, unsigned int> >, std::vector<unsigned long, std::allocator<unsigned long> > > > >') and 'const std::pair<const int, std::map<std::tuple<Code<3, unsigned int>, Code<3, unsigned int> >, std::vector<unsigned long, std::allocator<unsigned long> >, std::less<std::tuple<Code<3, unsigned int>, Code<3, unsigned int> > >, std::allocator<std::pair<const std::tuple<Code<3, unsigned int>, Code<3, unsigned int> >, std::vector<unsigned long, std::allocator<unsigned long> > > > > >')
ДОКОЛЕ?!!
−2
/*
Программа для генерации и вывода разряженной матрицы
Специально для сайта govnokod.ru
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
// Объявление переменных
const int first_index_size=20;
const int second_index_size=50;
char matrix_array[first_index_size][second_index_size];
enum border_style{
line,single
};
void borders(border_style matrix_border)
{
switch(matrix_border)
{
case 0:
for(int i=0; i<(second_index_size+2); i++)
std::cout<<"#";
std::cout<<"\n";
break;
case 1:
std::cout<<"#";
}
}
void rand_func_init()
{
// Инициализация функции rand()
srand(time(0));
rand();
}
void matrix_init_zero()
{
// Инициализация матрицы нулём
for(int i=0; i<first_index_size; i++)
for(int t=0; t<second_index_size; t++)
matrix_array[i][t]=0;
}
void matrix_init_rand()
{
// Заполнение матрицы
for(int i=0; i<first_index_size; i++)
{
int init_num=rand()%11;
while(init_num)
{
init_num--;
matrix_array[i][rand()%50]=149;
}
}
}
void matrix_print()
{
// Вывод матрицы
borders(line);
for(int i=0; i<first_index_size; i++)
{
borders(single);
for(int t=0; t<second_index_size; t++)
std::cout<<matrix_array[i][t];
borders(single);
std::cout<<"\n";
}
borders(line);
}
int main()
{
rand_func_init();
matrix_init_zero();
matrix_init_rand();
matrix_print();
return 0;
}
Разряженная матрица 20x50.
Количество ненулевых значений от 0 до 10.
+1
#include <iostream>
#include <type_traits>
#include <utility>
#include <array>
template<size_t Size, typename T, typename FunctorType, size_t... idx>
constexpr std::array<decltype(std::declval<FunctorType>().operator()(std::declval<T>())), Size>
map_impl(const std::array<T, Size> & arr, FunctorType && f, std::index_sequence<idx...>)
{
return std::array{ f(std::get<idx>(arr))... };
}
template<size_t Size, typename T, typename FunctorType>
constexpr std::array<decltype(std::declval<FunctorType>().operator()(std::declval<T>())), Size>
map(const std::array<T, Size> & arr, FunctorType && f)
{
return map_impl(arr, f, std::make_index_sequence<Size>{});
}
struct MyFunctor {
constexpr float operator()(int arg)
{
return static_cast<float>(arg * arg) / 2.0f;
}
};
int main()
{
constexpr std::array arr{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto arrMappedFunctor = map(arr, MyFunctor{});
auto arrMappedLambda = map(arr, [](int x) constexpr { return static_cast<float>(x * x) / 2.0f; });
for (auto && x : arrMappedFunctor) {
std::cout << x << ' ';
}
std::cout << std::endl;
for (auto && x : arrMappedLambda ) {
std::cout << x << ' ';
}
std::cout << std::endl;
return 0;
}
0.5 2 4.5 8 12.5 18 24.5 32 40.5 50
0.5 2 4.5 8 12.5 18 24.5 32 40.5 50
Метушня выходит на новый уровень: полноценный map в compile-time. Поддерживает как ручные функторы с перегруженным operator(), так и constexpr-лямбды. При помощи небольшой модификации возможно реализовать поддержку кортежей с произвольными типами.
0
inline constexpr size_t hardware_destructive_interference_size = implementation-defined;
This number is the minimum recommended offset between two concurrently-accessed objects to avoid
additional performance degradation due to contention introduced by the implementation.
Бля, пиздец. Модулей нет, строк нет, а комитет мутит какую-то хуиту космической глупости.
+2
#include <iostream>
#include <string>
int main()
{
std::string s1 = "";
const char s2[] = "";
std::cout << std::boolalpha
<< std::empty(s1) << std::endl
<< std::size(s1) << std::endl
<< std::empty(s2) << std::endl
<< std::size(s2) << std::endl;
s1.assign("", 1);
std::cout << std::empty(s1) << std::endl
<< std::size(s1) << std::endl;
system("pause");
return 0;
}
true
0
false
1
false
1
Ой-вэй, абстракции потекли!
−2
#include <iostream>
class ParusProject
{
public:
void start () const
{
std::cout << "Майбутнє вже тут!";
}
};
void MakeLvivGreatAgain()
{
ParusProject *city = new ParusProject;
city->start();
}
int main()
{
MakeLvivGreatAgain();
return 0;
}
Увидено на билборде.
1. Нахуя делать целый класс для выдачи одного неизменяемого стринга?
2. int main() {…} в оригинале не было, компилятор ругался ошибкой, пришлось самому дописывать.
3. Эквивалент хеллоуворлда с кириллицей на 21, мать его, строку.
+3
Чего такого умеют кресты, что не умеет Си?
Шаблоны - никто не пользует.
Перегрузка операторов - вообще дурь какая-то: не понятно чего ожидать от полюса или минуса.
Очевидный ответ - объекты , а так уж они нужны? Ну вот есть объект - библиотека работы с сокетами. Создал экземпляр, заполнил поля с адресом и портом, выполнил метод connect. Попользовался, освободил память. И чем оно лучше, чем если бы я запилил структуру и набор функций для работы с ней?
За скобки вынесем области применения, где преимущества объектного подхода очевидны: игры, ГУЙ и прочее. Поговорим об остальном.
Псто не мое.
Заходите на "огонек": https://www.linux.org.ru/forum/development/14396202
+1
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
string pswdGen(int quantity) {
srand(time(0));
char chars[] = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890@\#\$\%\&\-\+\!\/\_"; // Символы, из которых будет состоять пароль
string password;
for(int i = 0; i < quantity; i++) {
password += chars[rand() % (sizeof(chars)/sizeof(*chars))]; // Добавить рандомный символ из списка в пароль
}
return password;
}
int main() {
int charNo;
cout << "How many characters do you want in the password?" << endl;
cin >> charNo;
cout << "Your new password is: " << pswdGen(charNo) << endl;
return 0;
}
Генерит произвольные пароли. Говно?