- 1
- 2
- 3
// ...
c=getchar();
if(c==*" ") cout << "space";
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+26
// ...
c=getchar();
if(c==*" ") cout << "space";
+23
#include <iostream>
#include <stdlib.h>
#include <typeinfo>
using namespace std;
#define ololo for(volatile register int i=0;i<10;++i);
struct VB
{
virtual void f() const =0;
};
class V1: public VB
{
void f() const {ololo}
};
class V2: public VB
{
void f() const {ololo}
};
struct TU1
{
inline void f() const {ololo}
};
struct TU2
{
inline void f() const {ololo}
};
struct TUB
{
const type_info* type;
union
{
TU1 tu1;
TU2 tu2;
};
template<class T>
void ctor()
{
this->type=&typeid(T);
}
template<class T>
inline void call(const T& f)
{
if(this->type==&typeid(TU1))
f(this->tu1);
else
f(this->tu2);
}
};
enum {N=1000, N2=N*50};
int main() {
cout<<"ok"<<endl;
{
VB*v[N];
for(int i=0;i<N;++i)
if(rand()%2)
v[i]=new V1;
else
v[i]=new V2;
volatile clock_t a=clock();
for(int j=0;j<N2;++j)
for(int i=0;i<N;++i)
v[i]->f();
volatile clock_t b=clock();
cout<< (double)(b - a) / CLOCKS_PER_SEC<<endl;
}
cout<<"ok"<<endl;
{
TUB v[N];
for(int i=0;i<N;++i)
if(rand()%2)
v[i].ctor<TU1>();
else
v[i].ctor<TU2>();
struct Continuation
{
inline void operator()(const TU1& a) const {a.f();}
inline void operator()(const TU2& a) const {a.f();}
} cps;
volatile clock_t a=clock();
for(int j=0;j<N2;++j)
for(int i=0;i<N;++i)
v[i].call(cps);
volatile clock_t b=clock();
cout<< (double)(b - a) / CLOCKS_PER_SEC<<endl;
}
cout<<"ok"<<endl;
return 0;
}
http://ideone.com/plFaLM
Тут в соседней теме разгорелся спор, что быстрее - полиморфизм виртуальных функций или полиморфизм tagget union. По сути последнее - выбор по if нужной виртуальной функции. Говорят в Java быстрее второе.
Тема родилась из http://govnokod.ru/12025#comment158188
Получилось по результатам измерений:
Виртуальные функции: 1.8 секунд.
tagget union: 1.94 секунд.
Притом это всего 2 полиморфных типа в tagget union, а если рост числа полиморфных классов будет расти, то разрыв между виртуальными функциями и tagget union только увеличится. Притом производительность tagget union будет только падать.
Тема поднята ещё со взглядом на функциональные языки. Это ведь там так модны ADT с постоянным внутри ifподобным паттернматчингом по ним.
Жду указания на косяки или способы поднять производительность tagget union.
+20
void __fastcall TfРѕrm1::SpeedButton1Click(TobjРµct *Sender)
{
SpeedButton1->Enabled=false;
SpeedButton1->Caption=Edit1->Text;
if(Edit1->Text=="X")
Edit1->Text="0";
else
Edit1->Text="X";
if(SpeedButton1->Caption=="X" && SpeedButton2->Caption=="X" && SpeedButton3->Caption=="X" ||
SpeedButton4->Caption=="X" && SpeedButton5->Caption=="X" && SpeedButton6->Caption=="X" ||
SpeedButton7->Caption=="X" && SpeedButton8->Caption=="X" && SpeedButton9->Caption=="X" ||
SpeedButton1->Caption=="X" && SpeedButton4->Caption=="X" && SpeedButton7->Caption=="X" ||
SpeedButton2->Caption=="X" && SpeedButton5->Caption=="X" && SpeedButton8->Caption=="X" ||
SpeedButton3->Caption=="X" && SpeedButton6->Caption=="X" && SpeedButton9->Caption=="X" ||
SpeedButton1->Caption=="X" && SpeedButton5->Caption=="X" && SpeedButton9->Caption=="X" ||
SpeedButton3->Caption=="X" && SpeedButton5->Caption=="X" && SpeedButton7->Caption=="X")
ShowMessage("Ea?a caeii?aia, e?anoeee auea?aee");
else
if(SpeedButton1->Caption=="0" && SpeedButton2->Caption=="0" && SpeedButton3->Caption=="0" ||
SpeedButton4->Caption=="0" && SpeedButton5->Caption=="0" && SpeedButton6->Caption=="0" ||
SpeedButton7->Caption=="0" && SpeedButton8->Caption=="0" && SpeedButton9->Caption=="0" ||
SpeedButton1->Caption=="0" && SpeedButton4->Caption=="0" && SpeedButton7->Caption=="0" ||
SpeedButton2->Caption=="0" && SpeedButton5->Caption=="0" && SpeedButton8->Caption=="0" ||
SpeedButton3->Caption=="0" && SpeedButton6->Caption=="0" && SpeedButton9->Caption=="0" ||
SpeedButton1->Caption=="0" && SpeedButton5->Caption=="0" && SpeedButton9->Caption=="0" ||
SpeedButton3->Caption=="0" && SpeedButton5->Caption=="0" && SpeedButton7->Caption=="0")
ShowMessage("Ea?a caeii?aia, iieeee auea?aee");
}
+18
template <class TBitMap, int MMCROffset>
class TControllerMemoryMappedRegister: public TBaseControllerMemoryMappedRegister<MMCROffset>
{
public:
static void set(TBitMap::E Bit) { setBit(Bit); }
static void reset(TBitMap::E Bit) { resetBit(Bit); }
};
+15
#include <iostream>
#include <cxxabi.h>
#include <typeinfo>
int main(void)
{
uint8_t i = 63;
int status;
std::cout << i << std::endl;
char *realname = abi::__cxa_demangle(typeid(i).name(), 0, 0, &status);
std::cout << "Real type of uint8_t is: " << realname << std::endl;
delete (realname);
std::cout << (unsigned int)i << std::endl;
return 0;
}
...нативный 8bit-ый беззнаковый int.
+16
#include <functional>
using namespace std;
class O{};
class foo
{
public:
constexpr static auto anyGarbage = O(O(O(O())));//:Жаль, что написать auto anyGarbage = O(O(O(O()))); нельзя.
O anyGarbage2 = O(O(O(O())));
private:
int var;
public:
std::function<void(int)> setter=[this](int s){(void)s;/*var=s;*/};
};
Я хочу написать свои property, принимающие лямбды в качестве параметра setter и getter. Как сделать friend лямбду?
http://liveworkspace.org/code/39082e70108502c2e44c4fe6c5762d9a
+30
if( str[0] == '<' || str[1] == '?' || str[2] == 'x' || str[3] == 'm' || str[4] == 'l') {...}
Проверка на xml-ность
+25
template <typename T> struct Pool { static std::vector<T> data; };
std::vector<tbphys::Body> Pool<tbphys::Body>::data;
std::vector<Ball> Pool<Ball> ::data;
std::vector<Wall> Pool<Wall> ::data;
std::vector<Bat> Pool<Bat> ::data;
std::vector<Brick> Pool<Brick> ::data;
template <typename T, typename U> struct List
{
typedef T Head;
typedef U Tail;
};
struct End {};
typedef List<tbphys::Body, List<Brick, List<Bat, List<Ball, List<Wall, End> > > > > Components;
typedef List<Brick, List<Bat, List<Ball, List<Wall, End> > > > DrawableComponents;
typedef List<Brick, List<Ball, List<Bat, End> > > MovableComponents;
const size_t badindex = size_t(-1);
struct GameBody
{
size_t self,body,bat,brick,wall,ball;
template <typename T> size_t& IndexOf ();
template <> size_t& IndexOf <tbphys::Body> () {return body;}
template <> size_t& IndexOf <Bat > () {return bat;}
template <> size_t& IndexOf <Brick> () {return brick;}
template <> size_t& IndexOf <Wall > () {return wall;}
template <> size_t& IndexOf <Ball > () {return ball;}
template <typename T>
T& AddComponent ()
{
size_t index = Pool<T>::data.size();
Pool<T>::data.resize(index+1);
T& result = Pool<T>::data[index];
result.hostIndex = self;
IndexOf<T>() = index;
return result;
}
template <typename T> void SetBadIndex ()
{
IndexOf<T::Head> () = badindex;
SetBadIndex<T::Tail> ();
}
template <> void SetBadIndex <End> () {}
};
Сколько тут говнопаттернов крестоблядского крестоязыка?
+9
http://ideone.com/vvkWO4
+28
const std::string cyrillic = "аАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяЯ";
std::string cyrillic_toupper(std::string s)
{
if(cyrillic.find(s) == std::string::npos)
throw std::runtime_error(std::string("cyrillic_toupper(): ") + "'" + s + "' is not cyrillic char");
return cyrillic.substr(cyrillic.find(s) + 2, 2);
}