• Ошибка компиляции и подключения библиотеки к QT на Linux?

    myjcom
    @myjcom Куратор тега C++
    LIBS += -L"/home/artemon/C++/test1/SFML/lib/debug"
    LIBS += -L"/home/artemon/C++/test1/SFML/lib/release"
    Ответ написан
  • Как считать инфу из файла, записунную определнным образом и разбить в массивы (работа со строками)?

    myjcom
    @myjcom Куратор тега C++
    ну тогда
    spoiler
    filein.txt
    Petya,K221,1,2,3;Vasya,K222,4,5,6;Senya,K223,7,8,0;Goga,K224,1,2,3;

    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <string>
    #include <iterator>
    #include <algorithm>
    using namespace std;
    
    template<typename X = int>
    struct Data
    {
      X one;
      X two;
      X three;
      Data(X x1 = 0, X x2 = 0, X x3 = 0) : one{x1}, two{x2}, three{x3}
      {}
    };
    
    template<typename X = int>
    struct DataRecord
    {
      pair<string, string> text;
      Data<X> data;
      DataRecord(string _s1 = {}, string _s2 = {},
                 X _x1 = 0, X _x2 = 0, X _x3 = 0)
        : text{_s1, _s2}, data{_x1, _x2, _x3}
      {}
    };
    
    template<typename X = int>
    istream& operator>>(istream& is, DataRecord<X>& record)
    {
      char c;
      getline(is, record.text.first, ',');
      getline(is, record.text.second, ',');
      is >> record.data.one;
      is >> c;
      if(c == ',')
      {
        is >> record.data.two;
        is >> c;
        if(c == ',')
        {
          is >> record.data.three;
        }
      }
      is >> c;
      if(c != ';')
      {
        is.clear(ios_base::failbit);
      }
      return is;
    }
    
    struct DataSet
    {
      vector<DataRecord<>> records;
      DataSet() : records{}{}
      void load(string filename) noexcept;
      Data<> sumsByColumns() noexcept;
    };
    
    void DataSet::load(string filename) noexcept
    {
      ifstream in(filename);
      if(!in)
      {
        //...
        return;
      }
      copy(istream_iterator<DataRecord<>>{in}, {}, back_inserter(records));
    }
    
    Data<> DataSet::sumsByColumns() noexcept
    {
      Data<> result;
      for(const auto& rec : records)
      {
        result.one   += rec.data.one;
        result.two   += rec.data.two;
        result.three += rec.data.three;
      }
      return result;
    }
    
    int main()
    {
      DataSet ds;
      ds.load("C:\\infile.txt");
      Data<> result{ds.sumsByColumns()};
    
      for(const auto& rec : ds.records)
      {
        cout << rec.text.first << '\t'
             << rec.text.second << '\t'
             << rec.data.one << '\t'
             << rec.data.two << '\t'
             << rec.data.three << '\n';// Если формат записей в файле
                                       // построчный '\n' нужно убрать.
      }
    
      cout << "\nTotal:\t\t"
           << result.one << '\t'
           << result.two << '\t'
           << result.three << endl;
    }


    OUT
    Petya   K221    1       2       3
    Vasya   K222    4       5       6
    Senya   K223    7       8       0
    Goga    K224    1       2       3
    
    Total:          13      17      12

    Ответ написан
    1 комментарий
  • Почему ошибка ERROR C2678: ...?

    myjcom
    @myjcom Куратор тега C++
    для map<Point, bool> и map<Point, long>
    нужен пользовательский оператор
    bool operator<(const Point& p1, const Point& p2)
    {
      return (p1.x0 < p2.x0) && (p1.y0 < p2.y0);
    }

    Или
    bool operator<(const Point& a, const Point& b) 
    {
      return (a.x < b.x) || (a.y < b.y);
    }
    Ответ написан
  • Как сравнить 2 введенных слова?

    myjcom
    @myjcom Куратор тега C++
    Вы в std::string считываете.
    name1.compare(name2); //strcmp()
    https://ru.cppreference.com/w/cpp/string/basic_str...

    name1 == name2; //operator==
    https://ru.cppreference.com/w/cpp/string/basic_str...
    Ответ написан
    Комментировать
  • Как определить тип 'массив из 7 указателей на целое' в typedef?

    myjcom
    @myjcom Куратор тега C++
    typedef int* sevenPtr[7];
    int* a = nullptr;
    int b = 7;
    sevenPtr c = {a, a, a, &b, a, a, nullptr};


    Или
    using sevenPtr = int*[7];
    Ответ написан
    Комментировать
  • Почему при компиляции Си кода возникает ошибка "Segmentation fault (core dumped)"?

    myjcom
    @myjcom
    arrInterval и arrReplace ожидают указатель, а получают int, первым параметром и т.д.
    incompatible integer to pointer conversion passing 'int' to parameter of type 'int *'

    а z[15] (и остальное подобное) это вообще за пределами массива.
    array index 15 is past the end of the array (which contains 15 elements)

    Передавайте в них просто имя массива (оно же является указателем на первый элемент).
    int ans1 = arrInterval(x,5,start,end);
        printf("%d",ans1);
        int ans2 = arrInterval(y,10,start,end);
        printf("%d",ans2);
        int ans3 = arrInterval(z,15,start,end);
        printf("%d",ans3);
        
        arrReplace(x,5,ans1);
        arrReplace(y,10,ans2);
        arrReplace(z,15,ans3);
    Ответ написан
    Комментировать
  • Как решить проблему с циклом?

    myjcom
    @myjcom
    pole[n][m];
    может pole[m][n]; учитывая как циклы построены?

    в pole[m-1][...] находится мусор

    pole[...][n > 8] то же

    инит
    for(int i = 0; i < m-1; i++)
    {
      for (int j = 0; j < n; j++)
      {
        fscanf(f, "%d", &pole[i][j]);
        printf("%d ", pole[i][j]);	
      }
      printf("\n");
    }

    чтение
    for (int i = 0; i < m; i++)//??? i < m-1 ???
    {
      x = 0;
      for (int j = 0; j < n; j++)
      {
        switch (pole[i][j])
        {
          case 1: 
            brick(x, y, DarkGray); 
            printf("%d %d\n", x, y);
            break; //???
          case 0:;
          //...
        }
        x += 100;
      }
      y += 100;
    }
    Ответ написан
  • Как сделать на С++ подобное?

    myjcom
    @myjcom Куратор тега C++
    #include<iostream>
    #include<sstream>
    #include<string>
    #include<vector>
    #include<algorithm>
    #include<iterator>
    
    using namespace std;
    
    int main()
    {
        string s = "10 20 30   50 99         786 521        3";
        istringstream is(s);
        vector<int> c;
    
        copy(istream_iterator<int>(is), {}, back_inserter(c));
    
        for(int i : c)
        {
          cout << i << ' ';
        }
    
        int j = c[1] + c[2];
    
        cout << "j == " << j;
    }
    Ответ написан
  • Как сравнить с Enter?

    myjcom
    @myjcom Куратор тега C++
    Можно так
    #include<iostream>
    #include<string>
    
    using namespace std;
    
    int main()
    {
      setlocale(LC_ALL, "Russian");
      system("chcp 1251 > null");
      string s;
      cout << "Введите имя: ";
      while(getline(cin, s))
      {
        if(s.empty())
        {
          cout << "Вы не ввели имя!\n"
               << "Введите имя: ";
          continue;
        }
        break;
      }
      cout << "\nВаше имя: " << s
           << "\nНажмите любую клавишу...";
      cin.get();
    }

    Если правильнее, как пишет Артем Спиридонов,
    Тогда возможно так (Windows)
    #include<iostream>
    #include<string>
    #include<algorithm>
    #include<cctype>
    #include<clocale>
    
    using namespace std;
    
    /* functions from https://code-examples.net/ru/q/34ef7 */
    // trim from start (in place)
    static inline void ltrim(string &s)
    {
      s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](const auto ch) {
        return !isspace(ch);
      }));
    }
    
    // trim from end (in place)
    static inline void rtrim(string &s)
    {
      s.erase(std::find_if(s.rbegin(), s.rend(), [](const auto ch) {
        return !isspace(ch);
      }).base(), s.end());
    }
    
    // trim from both ends (in place)
    static inline void trim(string &s)
    {
      ltrim(s);
      rtrim(s);
    }
    
    int main()
    {
      setlocale(LC_ALL, "Russian");
      system("chcp 1251 > null");
      string s;
      cout << "Введите имя: ";
      while(getline(cin, s))
      {
        //upd
        replace_if(s.begin(), s.end(), [](const auto c){return iscntrl(c); }, ' ');
        trim(s);
        //end upd
    
        if(s.empty())
        {
          cout << "Вы не ввели имя!\n"
               << "Введите имя: ";
          continue;
        }
        break;
      }
      cout << "\nВаше имя: " << s
           << "\nНажмите любую клавишу...";
      cin.get();
    }

    Ответ написан
    Комментировать
  • Как сравнить и вывести сколько чисел в двух одномерных массивах равны [C / C++]?

    myjcom
    @myjcom Куратор тега C++
    если есть повторы?

    массив где есть повторы нужно передавать первым параметром.
    #include <algorithm>
    #include <iostream>
    using namespace std;
    
    template<typename T, int N, int M>
    auto count_match(T(&a)[N], T(&b)[M])
    {
      size_t match_count = 0;
      sort(begin(b), end(b));
      for(auto& val : a)
      { 
        if(binary_search(begin(b), end(b), val))
        {
          ++match_count;
        }
      }
      return match_count;
    }
    
    int main()
    {
      int  v[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 22};
      int v2[] = {0, 22, 33, 5, 4, 8, 9, 0, 13};
      
      std::cout << count_match(v, v2);
    
      cin.get();
    }

    если числа повторяются в обоих массивах
    нужно по другому делать,
    например с помощью std::map
    Ответ написан
  • Как изменить вектор внутри map c++?

    myjcom
    @myjcom Куратор тега C++
    map<string, vector<string>> mymap;
    string key = "asdf";
    
    auto elem {mymap.find(key)};
    if(elem != mymap.end())
    {
      //...
      elem->second.resize(42);
    }


    ...
    в С++17 можно еще проще/по-другому.
    Ответ написан
    Комментировать
  • Баг visual studio 2017?

    myjcom
    @myjcom Куратор тега C++
    https://msdn.microsoft.com/ru-ru/library/ms172677(...
    Практическое руководство. Изменение фрагмента кода после его вставки в код

    Используйте клавишу TAB для перемещения от одной точки замены до следующей. Для перемещения к предыдущей точке замены используйте сочетание клавиш SHIFT + TAB.
    Ответ написан
    Комментировать
  • Как получить количество букв в строке?

    myjcom
    @myjcom Куратор тега C++
    NaN
    #include<iostream>
    #include<string>
    #include<algorithm>
    //ru.cppreference.com/w/cpp/algorithm/count
    
    using namespace std;
    
    int main()
    {
      string s = "Asdk6949_glsjg+()(& *&%^%$df   gdfg     e$T#%Y KNUYNL  GIK5654";
      cout << count_if(s.begin(), s.end(), ::isalpha) << endl; 
    }
    Ответ написан
    2 комментария
  • Как вынести стоблец с меньшей суммой?

    myjcom
    @myjcom Куратор тега C++
    Найдите три отличия;)
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    #include<limits.h>
    
    int main()
    {
    	srand((unsigned)time(NULL));
    	const int n = 4;
    	const int m = 3;
    	int     idx = 0;
    	int   summa = 0;
    	int min_sum = INT_MAX;
    	int a[n][m];
    
    	for (int i = 0; i < n; i++)
    	{
    		for (int j = 0; j < m; j++)
    		{
    			a[i][j] = rand() % 20;
    			summa += a[i][j];
    			printf("a[%d][%d]=%d\n", i, j, a[i][j]);
    		}
    
    		if(min_sum > summa)
        {
          min_sum = summa;
          idx = i;
        }
    
    		printf("summa[%d]=%d\n", i, summa);
    		summa = 0;
    	}
    
      printf("min summa[%d]=%d\n", idx, min_sum);
    
      for(int i = 0; i < m; i++)
      {
        printf("a[%d][%d]=%d\n", idx, i, a[idx][i]);
      }
      return 0;
    }
    Ответ написан
    2 комментария
  • Как правильно передавать функцию как параметр C++?

    myjcom
    @myjcom Куратор тега C++
    если bt_rest это https://github.com/marcoschwartz/aREST/blob/master...
    то там по другому все устроено.

    copy is as in original
    // Functions array
      uint8_t functions_index;
      int (*functions[NUMBER_FUNCTIONS])(String);
      char * functions_names[NUMBER_FUNCTIONS];
    
    void function(char * function_name, int (*f)(String)){
    
      functions_names[functions_index] = function_name;
      functions[functions_index] = f;
      functions_index++;
    }
    Может так

    при условии что App будет в единственном экземпляре.
    #include<iostream>
    #include<string>
    /*
    * Будем считать, что std::string это String
    */
    #define NUMBER_FUNCTIONS 10
    struct aRest
    {
      uint8_t functions_index;
      int (*functions[NUMBER_FUNCTIONS])(std::string);
      char* functions_names[NUMBER_FUNCTIONS];
      //...
      aRest() : functions_index(0){};
      void function(char * function_name, int (*f)(std::string))
      {
        functions_names[functions_index] = function_name;
        functions[functions_index] = f;
        functions_index++;
      }
    };
    
    class App
    {
      aRest bt_rest;
    public:
      explicit App() : bt_rest(){};
      //...
      int startManufacturing(std::string command);
      void setup();
      void call(std::string s);// Для теста. Там то же по другому...
      //...
    };
    
    int App::startManufacturing(std::string command)
    {
      std::cout << "startManufacturing\n"
                << "with command " << command
                << " " << this << std::endl;
      return 1;
    }
    
    void App::setup()
    {
      bt_rest.function("startManufacturing", (int(*)(std::string))&startManufacturing);
      //reinterpret_cast<int(*)(std::string)>(&startManufacturing)
    }
    
    void App::call(std::string s)
    {
      bt_rest.functions[0](s);
    }
    
    int main()
    {
      App ap;
      ap.setup();
      ap.call("COMMAND");
    }
    или форкнуть aRest
    #include<iostream>
    #include<string>
    #include<functional>
    
    #define NUMBER_FUNCTIONS 10
    template<typename T>
    struct aRest
    {
      uint8_t functions_index;
    
      int (T::*functions[NUMBER_FUNCTIONS])(std::string);
      char* functions_names[NUMBER_FUNCTIONS];
      //...
      aRest() : functions_index(0){};
    
      void function(char * function_name, int(T::*f)(std::string))
      {
        functions_names[functions_index] = function_name;
        functions[functions_index] = f;
        functions_index++;
      }
    };
    
    class App
    {
      aRest<App> bt_rest;
    public:
      App() : bt_rest(){};
      //...
      int startManufacturing(std::string command);
      void setup();
      void call(std::string fn);
      //...
    };
    
    int App::startManufacturing(std::string command)
    {
      std::cout << "startManufacturing\n"
                << "with command " << command
                << " " << this << " " << std::endl;
      return 1;
    }
    
    void App::setup()
    {
      bt_rest.function("startManufacturing", &startManufacturing);
    }
    
    void App::call(std::string s)
    {
      std::mem_fn(bt_rest.functions[0])(this, s);
    }
    
    int main()
    {
      App ap;
    
      ap.setup();
    
      ap.call("COMMAND");
    }

    Ответ написан
  • Настройка Qt под Visual Studio?

    myjcom
    @myjcom
    Указывайте путь без qmake.exe
    Ответ написан
    Комментировать
  • Как вывести в консоль цветной текст из программы на C++ & Visual Studio под Windows?

    myjcom
    @myjcom Куратор тега C++
    windows 10
    EXAMPLE_OF_ENABLING_VIRTUAL_TERMINAL_PROCESSING

    code
    #include <stdio.h>
    #include <wchar.h>
    #include <windows.h>
    
    int main()
    {
      HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
      if (hOut == INVALID_HANDLE_VALUE)
      {
        return GetLastError();
      }
    
      DWORD dwMode = 0;
      if (!GetConsoleMode(hOut, &dwMode))
      {
        return GetLastError();
      }
    
      dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
      if (!SetConsoleMode(hOut, dwMode))
      {
        return GetLastError();
      }
    
      wprintf(L"\u001B[31mRed Text!\u001B[0mNormal Text\r\n");
      
      getchar();
      return 0;
    }

    OUT:
    5bd5f6b534a33368727521.png
    Ответ написан
    4 комментария
  • Что есть структура, а что оператор в C?

    myjcom
    @myjcom
    Переводчики имели ввиду структуры из https://ru.m.wikipedia.org/wiki/Структурное_програ...
    Они же statements https://en.cppreference.com/w/c/language/statements

    А не keyword struct https://en.cppreference.com/w/c/language/struct

    А operators это вообще https://en.cppreference.com/w/c/language/expressio...

    Это переводчики, такие переводчики.
    Оригинал посмотрите, как там написано.

    6th - 7th
    3.4 Control Structures
    Normally, statements in a program are executed one after the other in the order in which
    they’re written. This is called sequential execution. Various C statements we’ll soon discuss
    enable you to specify that the next statement to be executed may be other than the
    next one in sequence. This is called transfer of control.
    ...
    ...
    Bohm and Jacopini’s work demonstrated that all programs could be written in terms
    of only three control structures, namely the sequence structure, the selection structure
    and the repetition structure. The sequence structure is built into C. Unless directed otherwise,
    the computer executes C statements one after the other in the order in which
    they’re written.
    The flowchart segment of Fig. 3.1 illustrates C’s sequence structure.

    Bohm, C., and G. Jacopini, “Flow Diagrams, Turing Machines, and Languages with Only Two Formation
    Rules,” Communications of the ACM, Vol. 9, No. 5, May 1966, pp. 336–371.


    дальше везде statemens
    3.5 The if Selection Statement
    Selection statements are used to choose among alternative courses of action. For example,
    suppose the passing grade on an exam is 60. The pseudocode statement


    почему то переводят как Оператор выбора if

    Еще раз - Statements are fragments of the C program that are executed in sequence. -> см. https://en.cppreference.com/w/c/language/statements

    Operators -> https://en.cppreference.com/w/c/language/expressio...

    что бы не путаться Statement - инструкция. Operator - оператор
    в переводах может встречаться условный оператор if, составной оператор if ...

    короче говоря русский язык иногда/часто не имеет точных аналогов для перевода, поэтому трактуют как договорятся.
    Вот как переводить будут:
    C language Expressions
    An expression is a sequence of operators

    C language Statements
    Statements are fragments of the C program that are executed in sequence. The body of any function is a compound statement, which, in turn is a sequence of statements and declarations:

    There are five types of statements:
    1) compound statements
    2) expression statements
    3) selection statements
    4) iteration statements
    5) jump statements


    Compound statements
    A compound statement, or block, is a brace-enclosed sequence of statements and declarations.

    { statement | declaration...(optional) } (1)
    The compound statement allows a set of declarations and statements to be grouped into one unit that can be used anywhere a single statement is expected (for example, in an if statement or an iteration statement):

    if (expr) // start of if-statement
    { // start of block
      int n = 1; // declaration
      printf("%d\n", n); // expression statement
    } // end of block, end of if-statement


    И еще

    Не смотря на то что С++
    statement - инструкция
    Слово statement обычно переводят на русский термином "оператор". Таким образом, мы и привыкли, что if, while, case и т.п. – это операторы. К сожалению, в С++ этот перевод приводит к трудностям, поскольку имеется термин operator - словом "оператор" естественно было бы переводить его. Из возможных и встречавшихся в русской литературе переводов statement (утверждение, предложение, инструкция) в переводе книжки Струструпа, посвященной третьему стандарту С++, принят термин "инструкция".


    expression statement
    инструкция-выражение
    Инструкция, которая одновременно является и выражением. Примеры: присваивание, вызов функции.


    operator - оператор
    Встроенная операция языка, такая, как сложение. (Также перегруженная операция, задаваемая функцией-членом класса. -> к подмножеству Си не относится)

    English-Russian glossary of C + +. 2014.
    Ответ написан
    2 комментария
  • С++, как добавлять элементы в hash_map?

    myjcom
    @myjcom Куратор тега C++
    #include <iostream>
    #include <memory>
    #include <unordered_map>
    #include <list>
    
    struct Listener
    {
      std::string _name;
      Listener(std::string name) : _name{ name }{}
      ~Listener() = default;
    };
    
    using Listeners = std::unordered_map<std::string, std::list<Listener>>;
    
    class EventManager
    {
    public:
      EventManager(std::list<std::string>& eventTypes);
      //...
      ~EventManager() = default;
      void print()
      {
        for(const auto& v : *m_listeners)
        {
          std::cout << v.first << " -> ";
          for(const auto& s : v.second)
          {
            std::cout << s._name << ' ';
          }
          std::cout << std::endl;
        }
      }
    private:
      std::unique_ptr<Listeners> m_listeners;
    };
    
    EventManager::EventManager(std::list<std::string>& eventTypes)
                              : m_listeners { std::make_unique<Listeners>() }
    {
      auto insert_it(std::end( *m_listeners ));
      for (const auto &et : eventTypes)
      {
        insert_it = m_listeners->insert( insert_it, {et, {}} );
      }
    }
    
    int main()
    {
      std::list<std::string> events { "Open", "Move", "Close" };
      EventManager eManager{ events };
      eManager.print();
    }

    Еще свою хэш-функцию желательно написать.
    Ответ написан
    5 комментариев