- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
void Foo::singleShot()
{
QTime delay = QTime::currentTime().addMSecs(50);
while(QTime::currentTime() < delay ) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 5;
}
// do something
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
void Foo::singleShot()
{
QTime delay = QTime::currentTime().addMSecs(50);
while(QTime::currentTime() < delay ) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 5;
}
// do something
}
Вот такой бриллиант инженерной мысли, написанный с использованием фреймворка Qt.
Товарисч ещё спрашивал, чем его реализация хуже чем QTimer::singleShot() :D
+3
using namespace std;
#include <typeinfo>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <math.h>
#include <stdarg.h>
template <unsigned FRA,unsigned EXP>
struct F {
union{
float f;
unsigned ui;
unsigned ef : FRA+EXP;
struct
{
unsigned f : FRA;
unsigned e : EXP;
unsigned s : 1;
} s;
};
F (double x){f=x;}
F operator =(const double x) {
f=x; return *this;
}
#define NOOP ;
#define UN(OP,BODY, RET) float operator OP( ) { BODY; return RET;}
#define BIN(OP,BODY, RET) F operator OP(F other ) { BODY; return RET;}
#define BINF(OP,BODY,RET) F operator OP(const float other) { BODY; } BIN(OP,BODY,RET)
#define CMP(OP) bool operator OP(const F& other)
UN ( - , s.s^=1 , (f) )
BIN( += , f+=other.f , ( *this ) )
BIN( + , NOOP , { f+other.f} )
BIN( - ,++other.s.s , {*this+other} )
BIN( * , NOOP , fmul(f,{other}) )
BIN( / , div(other), ( *this ) )
BINF(*=, ui=fmul(*this ,{other}).ui, ( *this ) )
BINF(/=, ui=fmul(*this,rcp(other)).ui, ( *this ) )
CMP(==){
return other.ui==ui;
}
F out(string s) const{
printf("> %s%f\n",s.c_str(),f);
}
F plus(F other)
{
f+=other.f;
return *this;
}
F div(F other)
{
ui=fmul(rcp(other),{f}).ui;
return *this;
}
F sqrt()
{
s.e-=127;
ui>>=1;
s.f-=(s.f>>4);
s.e+=127;
return *this;
}
F pow(int n)
{
s.e-=127;
ui*=n;
ef+=(ef>>4);
ef-=(ef>>9);
s.e+=127;
return *this;
}
private:
static F rcp(F f) {
f.s.e=(~f.s.e-2);
f.s.f=(~f.s.f-2);
return f;
}
static F fmul(F r,F b)
{
r.s.s ^= b.s.s;
r.ef += ((r.s.f&b.s.f)>>4);
r.ef += b.ef ;
r.s.e+= 129;
return r;
}
};
using F32 = F<23,8>;
static F32 of32(float x)
Царь был прав. Во всём.
Патамучто это плавающий питух, который априори говно. И чем вы быстрее это поймёте, чем будет лучше.
В соответствии со своим пониманием сделал мммаксимально простую реализацию плавающих питухов произвольного размера.
Строго на интах.
Пример здесь:
uhttps://ideone.com/dDrj7s
0
https://github.com/dotnet/coreclr/blob/a589e3926a1780256fdb52376f8681fe047daf54/src/vm/i386/cgenx86.cpp#L1551-L1553
PAL_TRY(Param *, pParam, ¶m)
{
unsigned char buffer[16];
DWORD* dwBuffer = NULL;
DWORD maxCpuId = getcpuid(0, buffer);
if (maxCpuId < 1)
goto lDone;
dwBuffer = (DWORD*)buffer;
if (dwBuffer[1] == 'uneG') {
if (dwBuffer[3] == 'Ieni') {
if (dwBuffer[2] == 'letn') { // get SMT/multicore enumeration for Intel EM64T
С каких пор в одинарные кавычки можно писать больше одного символа? Это какое-то MSVC или что?
−1
// https://github.com/dotnet/coreclr/blob/a589e3926a1780256fdb52376f8681fe047daf54/src/vm/binder.cpp#L503-L511
const MscorlibBinder::OffsetAndSizeCheck MscorlibBinder::OffsetsAndSizes[] =
{
#define DEFINE_CLASS_U(nameSpace, stringName, unmanagedType) \
{ PTR_CSTR((TADDR) g_ ## nameSpace ## NS ), PTR_CUTF8((TADDR) # stringName), sizeof(unmanagedType), 0, 0, 0 },
#define DEFINE_FIELD_U(stringName, unmanagedContainingType, unmanagedOffset) \
{ 0, 0, 0, PTR_CUTF8((TADDR) # stringName), offsetof(unmanagedContainingType, unmanagedOffset), sizeof(((unmanagedContainingType*)1)->unmanagedOffset) },
#include "mscorlib.h"
};
Дух старой школы всё еще живет в майкрософт
−1
j123123, ты вообще пишешь полезный код или занимаешься
только тем, что постишь на говнокод советы космического масштаба
и комической же глупости о том, как всё оптимизировать?
+2
struct Bar {};
class Foo {
public:
Bar& bar() const { return *bp; }
private:
Bar b;
Bar * const bp = &b;
};
https://wandbox.org/permlink/7JPzrvslrUwbvREb
Как называется данный говнопаттерн?
−6
/* Q: Can someone recommend a more elegant way to achieve these compile-time constants? */
template <int> struct Map;
template <> struct Map<0> {static const int value = 4;};
template <> struct Map<1> {static const int value = 8;};
template <> struct Map<2> {static const int value = 15;};
template <int> struct MapInverse;
template <> struct MapInverse<4> {static const int value = 0;};
template <> struct MapInverse<8> {static const int value = 1;};
template <> struct MapInverse<15> {static const int value = 2;};
/* A: Another TMP approach for a linear search using C++11: */
#include <type_traits>
// === Types:
// Usage:
// Function<Map<x1,y1>,Map<x2,y2>,...>
template<int D, int R> struct Map { enum { domain=D, range=R }; };
template<typename ...A> struct Function {};
// === Metafunctions:
// Usage:
// ApplyFunction<x,F>::value
template<int I, typename M> struct ApplyFunction;
// Usage:
// ApplyFunctionInverse<x,F>::value
template<int I, typename M> struct ApplyFunctionInverse;
// ==== Example:
// Define function M to the mapping in your original post.
typedef Function<Map<0,4>,Map<1,8>,Map<2,15>> M;
// ==== Implementation details
template<typename T> struct Identity { typedef T type; };
template<int I, typename A, typename ...B> struct ApplyFunction<I, Function<A,B...> > {
typedef typename
std::conditional <I==A::domain
, Identity<A>
, ApplyFunction<I,Function<B...>> >::type meta;
typedef typename meta::type type;
enum { value = type::range };
};
template<int I, typename A> struct ApplyFunction<I, Function<A>> {
typedef typename
std::conditional <I==A::domain
, Identity<A>
, void>::type meta;
typedef typename meta::type type;
enum { value = type::range };
};
// Linear search by range
template<int I, typename A> struct ApplyFunctionInverse<I, Function<A>> {
typedef typename
std::conditional <I==A::range
, Identity<A>
, void>::type meta;
typedef typename meta::type type;
enum { value = type::domain };
};
template<int I, typename A, typename ...B> struct ApplyFunctionInverse<I, Function<A,B...> > {
typedef typename
std::conditional <I==A::range
, Identity<A>
, ApplyFunctionInverse<I,Function<B...>> >::type meta;
typedef typename meta::type type;
enum { value = type::domain };
};
// ==============================
// Demonstration
#include <iostream>
int main()
{
// Applying function M
std::cout << ApplyFunction<0,M>::value << std::endl;
std::cout << ApplyFunction<1,M>::value << std::endl;
std::cout << ApplyFunction<2,M>::value << std::endl;
// Applying function inverse M
std::cout << ApplyFunctionInverse<4,M>::value << std::endl;
std::cout << ApplyFunctionInverse<8,M>::value << std::endl;
std::cout << ApplyFunctionInverse<15,M>::value << std::endl;
}
Элегантненько.
s: https://stackoverflow.com/questions/26075969/compile-time-map-and-inverse-map-values
0
#include "stdafx.h"
#include<iostream>
#include<vector>
using namespace std;
/*
Задание: перемножить две матрицы и вывести результат на экран
*/
vector<vector<int>> inputToVector(int n,int m) {
vector<vector<int>>vec(n, vector<int>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> vec[i][j];
}
}
return vec;
}
template<class T>
void multiple(vector<T>a,vector<T>b,int x1,int y1,int y2) {
int ans = 0;
for (int i = 0; i < x1; i++) {
for (int j = 0; j < y2; j++) {
for (int k = 0; k < y1; k++) {
ans += a[i][k] * b[k][j];
}
cout << ans << '\t';
ans = 0;
}
cout << endl;
}
}
int main()
{
setlocale(LC_ALL, "Russian");
int x1, y1, x2, y2,temp;
cout << "Требуется вычислить произведение двух матриц А и В" << endl;
cout << "Введите размерность матрицы А" << endl;
cin >> x1 >> y1;
cout << "Введите элементы матрицы А" << endl;
vector<vector<int>>one = inputToVector(x1, y1);
cout << "Введите размерность матрицы B" << endl;
cin >> x2 >> y2;
cout << "Введите элементы матрицы B" << endl;
vector<vector<int>>two = inputToVector(x2, y2);
cout << "Результирующая матрица, полученная перемножением матрицы А на матрицу В" << endl;
multiple(one, two, x1, y1, y2);
system("pause");
return 0;
}
+2
#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;
int isMax(char mask[], int num, char in[]); //Функция проверки символа
int main(int argc, char* argv[])
{
if (argc == 1) {
cout << "Use PasswordGenerator [Mask] [quantity of passwwords] [Path to file]\n"; //Проверка входных параметров
return 1;
}
ofstream out; //Выходной файл
out.open(argv[3]); //Открываем файл с именем которое ввел пользователь
int len = 0; //Длина пароля
char mask[1024] = "hll"; //Маска пароля
char buff[1024] = { 0 }; //Буфер под пароль
double quant = 0; //Количество паролей в выходном файле
strcpy_s(mask, argv[1]); //копируем маску введённую пользователем
len = strlen(mask); //Узнаем длину
for (int ii = 0; ii < len; ii++) {
if ((mask[ii]= 'l') && (mask[ii]= 'h')&& (mask[ii]= 'n')) { //Проверка маски на корректность
cout << "Mask can be l h n\n"; //Маска может содержать только: l маленькие латинские буквы; h большие латинские буквы; n цифры
return 2;
}
}
quant = atoi(argv[2]); //Запоминаем количество комбинаций
if (quant == 0) { //Если пользователь ввел "0"
quant = 1; //То считаем все возможные комбинации
for (int ii = 0; ii < len; ii++) {
switch (mask[ii])
{
case 'l': quant *= 26; break; //26 - количество возможных букв
case 'h': quant *= 26; break;
case 'n': quant *= 10; break; //10 - количество возможных цифр
default:
break;
}
}
}
int ii = 0; //Нужная переменная
for (ii = 0; ii < len; ii++) { //Тут создается стартовая комбинация
switch (mask[ii]) //Например для nnllh будет 00aaA
{
case 'l': buff[ii] = 'a'; break;
case 'h': buff[ii] = 'A'; break;
case 'n': buff[ii] = '0'; break;
default:
break;
}
}
ii++;
buff[ii] = '\0'; //Добавляем маркер конца строки
double flagc = quant / 10; //Константа для поиска процента завершения
double flag = flagc; //Переменная процента завершения
int per = 1; //Множитель процента
for ( ii = 0; ii < quant; ii++) { //Основной цикл
out << buff << endl; //Сохраняем пароль в файл
if (ii >= flag) { //Если программа завершила 10%
cout << per * 10 << "%\n"; //Выводим проценты
per++;
flag += flagc;
}
for (int ii = len - 1; ii >= 0; ii--) { //начинаем посимвольный перебор с конца строки
if (isMax(mask, i, buff) == 1) { //Если встречаем последний возможный символ в данной позиции, то меняем его на стартовый
switch (mask[ii])
{
case 'l': if (buff[ii] == 'z')buff[ii] = 'a'; break;
case 'h': if (buff[ii] == 'Z')buff[ii] = 'A'; break;
case 'n': if (buff[ii] == '9')buff[ii] = '0'; break;
default:
break;
}
continue; //Переход в следующую итерацию цикла
}
buff[ii] +=1; //Сама инкрементация пароля
break; //Конец внутреннего цикла
}
}
return 0;
}
int isMax(char mask[], int num, char in[]){
switch (mask[num])
{
case 'l': if (in[num] == 'z')return 1; else return 0; //Если символ последний, то возвращаем "1", в противном случае "0"
case 'h': if (in[num] == 'Z')return 1; else return 0;
case 'n': if (in[num] == '9')return 1; else return 0;
default:
break;
}
}
Простой генератор паролей на C++
https://codeby.net/forum/threads/prostoj-generator-parolej-na-c.61639/
0
#include "stdafx.h"
#include<iostream>
#include<map>
#include<set>
#include<string>
#include<fstream>
#include<iomanip>
#include<algorithm>
//#include<algorithm>
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
multimap<string, int> mp;
multimap<string, int>::iterator it;
multimap<string, int>::iterator mit;
pair<multimap<string,int>::iterator, multimap<string, int>::iterator> pt;
set<int>nset;
string word;
char c = ' ';
char s[256];
fstream inOut;
inOut.open("text.txt", ios::in);
for (int i = 1; i < 500; i++) {
inOut.getline(s, 256);
char* pch;
pch = strtok(s, " ,-:");
while (pch != NULL) {
word = string(pch);
transform(word.begin(), word.end(), word.begin(), ::tolower);
mp.insert(pair <string, int>(word, i));
//cout « pch «'\t'«i« endl;
pch = strtok(NULL, " ,-:");
}
}
inOut.close();
set<string>set;
string tmp;
for (mit = mp.begin(); mit != mp.end(); mit++) {
tmp = (*mit).first;
if (set.find(tmp) != set.end()) {
continue;
}
else {
set.insert(tmp);
cout<<setw(15) << tmp << '\t';
pt = mp.equal_range(tmp);
for (it = pt.first; it != pt.second; ++it) {
nset.insert(it->second);
}
//cout << nset.size() << " ";
for (it = pt.first; it != pt.second; ++it) {
cout << it->second << ' ';
}
nset.clear();
cout << endl;
}
}
system("pause");
return 0;
}
Программа считывает слова сортирует и выдаёт все номера строк где данное слово встречается