Рабочий стол > DL Руководство пользователя > Полезные факты о С++ > Просмотр
Полезные факты о С++ Войти | Зарегистрироваться   Просмотр версии для печати текущей страницы.

Добавлен Egor, отредактирован Egor Oct 09, 2016
Метки: 
(нет)

Вы просматриваете старую версию (v. 1) этой страницы.
Последняя версия - v. 8 , последнее редактирование Oct 09, 2016 (просмотр отличий | )
просмотр истории страницы | просмотр следующей версии >>

- 1. Маленькие хитрости 

     - контроль корректности при исполнении программы
       assert(z[i] != LLONG_MAX);
   
     - измерение времени выполнения и производительности процесора
       cerr << fixed << setprecision(0)
            << "TIME = " << clock() / (ld)CLOCKS_PER_SEC * 1000 << "\n";
  
     - для выхода из множества циклов внутри процедуры 
       return 0

     - 1LL - константа 1 типа long long
       ans+=1LL*(выражение типа int), когда сумма превысит int

     - да и нет по русски

p1.cpp
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#include <bits/stdc++.h>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;using namespace std;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int main()
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int n,m,a\[50\],i;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;char d,dd,u,uu,uuu;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;d=164; dd=160; u=173; uu=165; uuu=226;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;cin >> m >> n;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(i=0;i<n;i++) cin >> a\[i\]; i=0;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;while(i<n && a\[i\]\!=m) i++;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(i==n) cout << u << uu << uuu;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else cout << d << dd;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}

           

0. Для передачи значения обратно из функции в вызывающую программу
   пишем знак & (передать адрес), например
     bool Good(int &x)

Unknown macro: {...}
 

   Пример

p2.cpp
&nbsp; &nbsp; &nbsp;#include <bits/stdc++.h>
&nbsp; &nbsp; &nbsp;using namespace std;
&nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp;void Split(int x, int &x1, int &x2, int &x3)
&nbsp; &nbsp; &nbsp; &nbsp;{
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x1=x%10;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x3=x/100;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x2=(x/10) % 10;
&nbsp; &nbsp; &nbsp; &nbsp;}
&nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp;int main()
&nbsp; &nbsp; &nbsp;{
&nbsp; &nbsp; &nbsp; int i,i1,i2,i3,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j,j1,j2,j3,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n,a2,a3;
&nbsp; &nbsp; &nbsp; cin >> n;
&nbsp; &nbsp; &nbsp; ...
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Split(i,i1,i2,i3);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Split(j,j1,j2,j3);
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (((i1+i2+i3)==(j1+j2+j3)) && (abs(i-j)>a3))
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a3=abs(i-j);
&nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp;}

1. Порядок вычисления логических выражений 
   Для  && слева направо
   && гарантирует что второй операнд не вычисляется, если первый - ложь.

   while ( (k<=es) && (s[k]!=t)  ) k++;

   к s[k] не происходит обращения, если k>es

2. 

iostream::sync_with_stdio(false);
   cin.tie(NULL);


   - для ускорения потокового ввода

3.  Объявление файлов 

   (стандартный потоковый ввод-вывод)

   ifstream cin("round.in");
   ofstream cout("round.out");

 
   или так

   freopen("auto.in", "r", stdin);
   freopen("auto.out", "w", stdout);

   или так - потоковый ввод-вывод 
             с файловыми переменными fin fout

   ifstream fin("perimeter.in");
   ofstream fout("perimeter.out");
   fin  >> n;
   fout << n;

   Работа с файлом, если он есть 
   и с клавиатурой в противном случае

   if (fopen("boarding.in", "r")) 
     

Unknown macro: {        freopen("boarding.in", "r", stdin);        freopen("boarding.out", "w", stdout);      }

   Работа с файлом, на своей машине 
   и с клавиатурой/экраном на DL

   #ifndef CONTEST
           ifstream cin("input.txt");
           ofstream cout("output.txt");
   #endif

   Работа до конца входного файла

   ifstream cin("input.txt");
   ofstream cout("output.txt");

   cin >> a;
   while (not cin.eof()) 
     

Unknown macro: {       ...       cin >> a;     }

4.           Знаковые            
   2 байта - int   
   4 байта - long int
   8 байт  - long long

   беззнаковые  - unsigned (int, long int, long long)

5. Константы
  

 #define MaxN 1e5; 
   const int MaN = 1e5;

6. 

ans = (ans==INF) ? -1 : ans;  // если ans=INF занесnи туда -1


          условие     true  false

7. Как вернуть значение в вызывающую программу ?
   - написать & перед именем переменной 
      то есть в подпрограмму передаётся не значение, а адрес
      и потому в подпрограмме модифицируется сама переменная
      из вызывающей программы

part.cpp
&nbsp; &nbsp; &nbsp; bool Found(int &x, int &y)
&nbsp; &nbsp; &nbsp; &nbsp; {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i=0; i<8; i++)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int j=0; j<8; j++)
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (not Marked\[i\]\[j\])
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { x=i; y=j; return true;};
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;
&nbsp; &nbsp; &nbsp; &nbsp; }

8. Работа в Codeblocks

     - ДУБЛИРОВАНИЕ СТРОКИ
         ctrl+D
     - СДВИГ ТЕКСТА ВПРАВО/ВЛЕВО
         отмечаем несколько строк и можно сдвигать их 
         вправо - клавишей   TAB
         влево  - клавишами  Shift + TAB

9. Массив инициализируется нулями при объявлении?

Массивы в C++ по стандарту по умолчанию не обнуляются.
Но для обнуления есть отдельный краткий синтаксис:
http://stackoverflow.com/questions/1920430/c-array-initialization

Поэтому можно писать по вкусу:

int a[10] =

Unknown macro: {0}

;
int a[10] = {};
int a[10]

;
int a[10] {};

Тогда отдельный обнуляющий цикл не понадобится.

 
   Некоторые компиляторы, такие как GCC, заполняют все элементы массива нулями при его создании.
   https://code-live.ru/post/cpp-arrays/

   А вот эта программа без ручного обнуления не проходит: 

p3.cpp
\#include <bits/stdc++.h>
using namespace std;

int main()&nbsp;
{
&nbsp; freopen("input.txt", "r", stdin);
&nbsp; freopen("output.txt", "w", stdout);

&nbsp; int g\[15\],n,m,k,i,x,y,ans;

&nbsp; cin>> n >> m >> k;

&nbsp; for (i=0; i<n; i++) g\[i\]=0; &nbsp; &nbsp; &nbsp; &nbsp; // без этого оператора не сдаётся

&nbsp; for (i=0; i<n; i++)
&nbsp; &nbsp; {
&nbsp; &nbsp; &nbsp; cin >> x >> y;
&nbsp; &nbsp; &nbsp; g\[--x\]=1; g\[--y\]=1;
&nbsp; &nbsp; }
&nbsp; ans=0;
&nbsp; for (i=0; i<n; i++)
&nbsp; &nbsp; if (g\[i\]==0) ans++;
&nbsp; cout << ans;
}

 

Powered by Atlassian Confluence, the Enterprise Wiki. (Version: http://www.atlassian.com/software/confluence Build:#2.6.1 916) - Ошибка/новая особенность - Свяжитесь с Администраторами