1. C++ / Говнокод #20403

    +4

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    #include <IO/Stream.h>
    #include "Algorithms/Range.h"
    #include "Algorithms/RangeConstruct.h"
    #include "Algorithms/RangeIteration.h"
    #include "Algorithms/RangeMutation.h"
    
    using namespace IO;
    using namespace Range;
    
    int main()
    {
      Console.PrintLine("Есть нормальная поддержка Юникода в консоли, даже на винде.");
      Console.PrintLine("Тестируется текст с кириллицей, греческим алфавитом αβγδεζηθικλμνξο, а также с иероглифами ㈇㌤㈳㌛㉨.");
      Console.PrintLine("Иероглифы не отображаются в консоли, потому что консольный шрифт их не содержит, но копируются оттуда нормально.");
    
       StringView strs[] = {"hello", "world"};
      StringView strs1[]  = {"range", "testing", "program"};
      StringView strs2[] = {"C++", "крут"};
    
      Console.PrintLine("В тесте используются три массива:", endl, strs, endl, strs1, endl, strs2);
      Console.PrintLine(endl, "Пример вывода initializer list:", endl, AsRange<double>({4353.435, 3243.23, 21.421, 12355.5, 64532}));
    
      auto fib = Recurrence(Algo::Op::Add<int>, 1, 1);
    
      Array<int> fibArr;
      fibArr.SetCountUninitialized(15);
      auto copyResult = fib.Take(15).Copy(fibArr());
      Console.PrintLine(endl, "Последовательность Фибоначчи в массиве: ", endl, fibArr());
      Console.PrintLine(endl, "Вторая половина того же массива задом наперёд: ", endl, fibArr($/2, $).Retro());
    
      fib.Drop(5).Take(15).Copy(fibArr.Insert($));
      Console.PrintLine(endl, "Добавляем 15 чисел Фибоначчи, начиная с пятого, в конец. Новое содержимое массива: ");
      Console.PrintLine(fibArr());
    
      Console.PrintLine(endl, "Объединяем элементы различных диапазонов в диапазоне кортежей: ", endl, ToString(
        Zip(
          fib.Take(30),
          Chain(AsRange(strs), AsRange(strs1), AsRange(strs2)).Cycle().Take(20),
          Recurrence([](int a, int b){return a*2+b;}, 1, 1).Take(17).Cycle().Drop(3).Take(22),
          fib.Take(19).Cycle().Drop(5).Take(50).Stride(3),
          Recurrence(Algo::Op::Mul<ulong64>, 2ull, 3ull).Take(9)
        ), 
        ",\n  ", "[\n  ", "\n]"));
    
    
      static const StringView pattern[] = {"pattern", "fills", "range"};
      Chain(AsRange(strs), AsRange(strs1), AsRange(strs2)).FillPattern(AsRange(pattern));
    
      Console.PrintLine(endl, "Поменяли сразу три массива одним вызовом FillPattern: ");
      Console.PrintLine(strs, endl, strs1, endl, strs2, endl);
    
      Console.PrintLine("11-й элемент зацикленного массива строк: ", endl, AsRange(strs).Cycle().Take(11).Tail(1), endl);
      Console.PrintLine("Перевёрнутый массив строк: ", endl, AsRange(strs).Retro(), endl);
      Console.PrintLine("Зациклили первые два элемента массива и взяли 10 из них:");
      Console.PrintLine(AsRange(strs1).Take(2).Cycle().Take(10) );
      Console.PrintLine("Между массивом строк и 5 числами Фибоначчи выбрали второе в рантайме: ");
      Console.PrintLine(Choose(AsRange(strs1), fib.Take(5).Map([](int x){return ToString(x);}), true) );
    
      static const size_t indices[] = {1,1,1,2,2,0,2,1,0};
      Console.PrintLine(
          RoundRobin(
            AsRange(strs1).Indexed(AsRange(indices)),
            Repeat(StringView("Test"), 5),
            AsRange(strs1),
            AsRange(strs2)
          ));
      
    
      Console.PrintLine(endl, "Введите строки, которые войдут в диапазон строк. В конце введите \"end\".");
      Console.PrintLine("Вы ввели следующие строки:", endl, ToString(Console.ByLine("end")) );
    
      int arr[]={1, 4, 11, 6, 8};
      Console.PrintLine("max{1, 4, 11, 6, 8} = ", AsRange(arr).Reduce(Algo::Op::Max<int>));
    
      Console.PrintLine("Генерация 100 случайных чисел от 0 до 999 и вывод квадратов тех из них, которые делятся на 7: ", endl,
        Generate([](){return math::urandom()%1000;}).Take(100)
        .Filter([](uint x) {return x%7==0;})
        .Map(math::sqr<uint>)
      );
    
      return 0;
    }

    Давно здесь не было моих велосипедов. А они с тех пор сильно эволюционировали, я даже многие фичи из языка D смог перенести в C++.
    Вывод в консоль и обсуждение здесь: http://www.gamedev.ru/flame/forum/?id=216045&page=99#m1481

    gammaker, 20 Июля 2016

    Комментарии (7)
  2. C++ / Говнокод #20397

    +7

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    #include <iostream>
    
    struct Test {
    	operator auto() -> bool { return true; }
    };
    
    int main() {
    	std::cout << std::boolalpha << Test() << std::endl;
    }

    operator auto() завезли!
    http://ideone.com/sGxeQn

    Antervis, 20 Июля 2016

    Комментарии (22)
  3. C++ / Говнокод #20392

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    #define __DEBUG
    #ifdef __DEBUG
        #define print_pair(p) do{std::cout << "(" << ((p).first + 1) << ", "\
                                << ((p).second + 1) << ")" << std::endl;}while(0);
    #endif
    
    Graph::result
    Graph::dijkstra (int start)
    {
    #ifdef __DEBUG
        std::cout << "Dijkstra algorithm tracing:" << std::endl;
    #endif
        distances[start] = 0;
        std::set<std::pair<int, int>> q;
        q.insert (std::make_pair(distances[start], start));
        while (!q.empty())
        {
    #ifdef __DEBUG
            std::cout << "top element of a set: ";
            print_pair(*q.begin());
    #endif
            int current = q.begin()->second;
            q.erase(q.begin());
            for (int i = 0; i < adj[current].size(); ++i)
            {
    #ifdef __DEBUG
        std::cout << "current vertex: " << (current + 1);
        std::cout << " ad current state of distances array is: " << std::endl;
        for (auto i: distances)
            std::cout << i << " ";
        std::cout << std::endl;
    #endif
                int to = adj[current][i].second;
                int length = adj[current][i].first;
                // Relaxations
                if (distances[to] > distances[current] + length)
                {
    #ifdef __DEBUG
        std::cout << "relaxation for edge (" << current << ", " << to << ") ";
        std::cout << "with weight " << length << std::endl;
    #endif
                    
                    q.erase(std::make_pair(distances[to], to));
                    distances[to] = distances[current] + length;
                    path[to] = current;
                    q.insert(std::make_pair(distances[to], to));
                }
            }
        }
        // Replace INF by -1
        std::replace (distances.begin(), distances.end(), INF, -1);
        return distances;
    }

    Я у мамы решил подебажить как мыщъх дебажил при помощи отладочной печати. Вот что получилось.

    HiewMorjowie, 18 Июля 2016

    Комментарии (44)
  4. C++ / Говнокод #20390

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    96. 96
    97. 97
    98. 98
    99. 99
    #define CREATE_EVENT_LISTENER(_elname, arg1_type, arg1_name) \
    class _elname : public EventListener	 \
    {	 \
    private:	 \
    	class IContainer	 \
    		{	 \
    	public:	 \
    		virtual void Call(arg1_type arg1_name) = 0;	 \
    		virtual ~IContainer() {}	 \
    		};	 \
    	 \
    	class FunctionContainer : public IContainer	 \
    		{	 \
    	private:	 \
    		typedef void(*__CallbackPtr)(arg1_type);	 \
    	public:	 \
    		FunctionContainer(__CallbackPtr fn)	 \
    				{	 \
    			this->fn = fn;	 \
    				}	 \
    	 \
    		virtual void Call(arg1_type arg1_name)	 \
    				{	 \
    			fn(arg1_name);	 \
    				}	 \
    	 \
    	private:	 \
    		__CallbackPtr fn;	 \
    		};	 \
    		 \
    	template<class T, class Q>	 \
    	class MethodContainer : public IContainer	 \
    		{	 \
    	public:	 \
    		MethodContainer(T method, Q _this)	 \
    				{	 \
    			this->method = method;	 \
    			this->_this = _this;	 \
    				}	 \
    	 \
    		virtual void Call(arg1_type arg1_name )	 \
    				{	 \
    			(_this->*method)(arg1_name);	 \
    				}	 \
    	 \
    	private:	 \
    		T method;	 \
    		Q _this;	 \
    		};	 \
    public:	 \
    	typedef void(*__FN_CALLBACK)(arg1_type);	 \
    	 \
    	_elname(__FN_CALLBACK fn)	 \
    		{	 \
    		this->container = new FunctionContainer(fn);	 \
    		}	 \
    	 \
    	template <class T, class Q>	 \
    	_elname(T method, Q _this)	 \
    		{	 \
    		this->container = new MethodContainer<T, Q>(method, _this);	 \
    		}	 \
    	 \
    	void Call(arg1_type arg1_name)	 \
    		{	 \
    		container->Call(arg1_name);	 \
    		}	 \
    	 \
    	virtual ~_elname()	 \
    		{	 \
    		delete this->container;	 \
    		}	 \
    private:	 \
    	IContainer* container;	 \
    };	 \
    
    #define CREATE_EVENT(_ename, _elname, arg1_type, arg1_name) \
    class _ename : public Event	 \
    {	 \
    public:	 \
    	void AddListener(_elname* listener)	 \
    		{	 \
    		Event::AddListener(listener);	 \
    		}	 \
    	 \
    	void Handle(arg1_type arg1_name)	 \
    		{	 \
    		for (size_t i = 0; i < this->listeners.size(); i++)	 \
    												{	 \
    			((_elname*)listeners[i])->Call(arg1_name);	 \
    												}	 \
    		}	 \
    	 \
    	void RemoveListener(_elname* listener)	 \
    		{	 \
    		Event::RemoveListener(listener);	 \
    		}	 \
    	 \
    };	 \

    Я когда то это написал. Думал, это хорошая идея...
    Полный файл: https://github.com/arhyme/CPP_EVENTS/blob/master/Event.h

    Avery, 18 Июля 2016

    Комментарии (59)
  5. C++ / Говнокод #20381

    +5

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    void add( std::string *str, std::string *addstr)
    {
      if(!strlen(addstr->c_str()))
        return;
    
      int len = strlen(str->c_str());
      if( len )
      {
        if((str->c_str())[len-1] != ';')
          *str = *str + ";";
    
        *str = *str + *addstr;
      }
      else
        *str = *addstr;
    
      len = strlen(str->c_str());
      if((str->c_str())[len-1] == ';')
    
      *str = str->substr(0,len-1);
    }

    kocmoc, 15 Июля 2016

    Комментарии (2)
  6. C++ / Говнокод #20373

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    #include <iostream>
    #include <vector>
    using namespace std;														
    
    
    int main() {
    	victor<bull> v = {1,0,1};
    	for(auto&& i : v) //Если удалить один &, то не скомпилируется
    		cout<<i<<endl;
    	return 0;
    }

    http://rextester.com/DBCM68277

    laMer007, 13 Июля 2016

    Комментарии (34)
  7. C++ / Говнокод #20371

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    SoftwareCommon::params::IParamLoader::TypeDb SettingsProxy::getTypeDb() const
    	{
    		try
    		{
    			auto type = Locator::Services::Locator->Resolve<ISettings^>()->Type;
    			switch (type)
    			{
    			case decltype(type)::Firebird: return IParamLoader::Firebird;
    			case decltype(type)::MSSQL: return IParamLoader::MSSQL;
    			default:
    				throw std::runtime_error("Unsupported db type");
    			}
    		}
    		catch (Exception ^ex)
    		{
    			throw std::runtime_error(marshal_1251(ex->ToString()));
    		}
    	}

    laMer007, 13 Июля 2016

    Комментарии (5)
  8. C++ / Говнокод #20365

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    // p2.cpp : Defines the entry point for the console application.
    //   Язык Visual C++ 7.0
    //   Консольное приложение
    //   13.07.2016
    
    #include "stdafx.h"
    #include <conio.h>
    
    int aa (int, int, int);
    void ab (int);
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	int a, b, c, d, e;
    	int f;
    
    	for (a = 0; a < 4; a++)
    		for (b = 0; b < 4; b++)
    			for (c = 0; c < 4; c++)
    				for (d = 0; d < 4; d++)
    					for (e = 0; e < 4; e++)
    					{
    						f = aa (1, a, 2);
    						f = aa (f, b, 3);
    						f = aa (f, c, 4);
    						f = aa (f, d, 5);
    						f = aa (f, e, 6);
    
    						if (f == 35)
    						{
    							printf ("((((1 "); ab (a);
    							printf ("2) "); ab (b);
    							printf ("3) "); ab (c);
    							printf ("4) "); ab (d);
    							printf ("5) "); ab (e);
    							printf ("6 = 35.\n");
    						}
    					}
    
    	getch ();
    	return 0;
    }
    
    
    int aa (int a, int b, int c)
    {
    	switch (b)
    	{
    		case 0: return a + c;
    		case 1: return a - c;
    		case 2: return a * c;
    		case 3: return a / c;
    	}
    
    	return 0;
    }
    
    void ab (int a)
    {
    	switch (a)
    	{
    		case 0: printf ("+ "); break;
    		case 1: printf ("- "); break;
    		case 2: printf ("* "); break;
    		case 3: printf ("/ "); break;
    	}
    }

    Задача: В написанном выражении ((((1 ? 2) ? 3) ? 4) ? 5) ? 6 вместо каждого знака ? вставить знак одного из четырёх арифметических действий: +, -, *, / так, чтобы результат вычислений равнялся 35.

    FrontlineReporter, 13 Июля 2016

    Комментарии (67)
  9. C++ / Говнокод #20359

    +4

    1. 1
    2. 2
    auto highPriority = static_cast<bool>(features(w)[5]);
    // Тип features(w) - std::vector<bool>

    Скотт Майерс. Эффективный и современный С++.

    Antervis, 10 Июля 2016

    Комментарии (35)
  10. C++ / Говнокод #20355

    +4

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    enum SomeEnum
    {
        // ...
        SomeShit = 0xD6,
        // ...
    };
    
    // ....
    
        Byte opcode = ReadSomeShit<Byte>();  // функция читающая raw memory в нужном представлении
        // из raw memory считано значение эквивалентное 0xD6
        // ...
        if (opcode == SomeShit) // условие не выполнилось
        {
            // do stuff
        }
    
    // ...

    почему? а потому что кто додумался до
    typedef char Byte;
    который (хоть и не обязан быть, но) знаковый

    и даже сраного ворнинга не выдало
    причина правда обнаружилась достаточно быстро, ибо в дебагере в opcode красовалось -42 а в SomeShit 214

    https://ideone.com/02TpT7 на первый взгляд вызывает когнитивный диссонанс
    обожаю кресты

    meinf, 08 Июля 2016

    Комментарии (18)