2 Podstawy



Zmienne

                                       bits
short int                         2 -32,768 to 32,767
unsigned short int         2 0 to 65,535
unsigned int                 4 0 to 4,294,967,295
int                                 4 -2,147,483,648 to 2,147,483,647
long int                         8 -2,147,483,648 to 2,147,483,647
unsigned long int         4 0 to 4,294,967,295
long long int                 8 -(2^63) to (2^63)-1
unsigned long long int 8 0 to 18,446,744,073,709,551,615
signed char                 1 -128 to 127
unsigned char                 1 0 to 255

#include <stddef.h>

size_t
Unsigned integral type of the result of the sizeof operator.

Fixed-width integers

These are defined as follows:
NameTypeRangeNotes
int8_t1 byte signed-128 to 127Treated like a signed char on many systems. See note below.
uint8_t1 byte unsigned0 to 255Treated like an unsigned char on many systems. See note below.
int16_t2 byte signed-32,768 to 32,767
uint16_t2 byte unsigned0 to 65,535
int32_t4 byte signed-2,147,483,648 to 2,147,483,647
uint32_t4 byte unsigned0 to 4,294,967,295
int64_t8 byte signed-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
uint64_t8 byte unsigned0 to 18,446,744,073,709,551,615
C++ officially adopted these fixed-width integers as part of C++11. They can be accessed by including the cstdint header, where they are defined inside the std namespace.

#include<cstdint>

..........


standardowo typy wbudowane wg definicji nie są określone po długości bajtów ale po pojemności liczb (patrz C) (jeśli chcesz wymusić długość bajtową patrz tabelka powyżej)

int  max =    std::numeric_limints<int>::max();               zwróci max ,   ::min() - zwróci min

CONST - stała

to samo co za pomocą preprocesora
#define MAX_INIT 5
ale on po prostu zamieni ciąg na 5 podczas kompilacji...


cout:
manipulator oct    hex   dec   / albo setbase(16) ??
int liczba=255
cout<<"Liczba 16tkowo"<<hex<<liczba;   raz uruchomiony hez na zmiennej liczba-działa
więc w następnej lini jeśli chcemy w dziesiętnym to <<dec<liczba;




Referencje (alias)
int a=5;
int &b=a;

b jest referancją do a. zapis do b zmieni a, zamiana a zmieni b

const int &k=a;

za pomocą k nie zmienimy a, ale zmiana a zmieni k

Referancja może być przypisana do czegoś co ma adres (inna zmienna).
Referancja jest wskaźnikiem, czyli jeśli przekazywana do funkcji jako parametr to zmiana w funkcji wpłynie na a.



Typedef , using
pozwala na istniejącemu już typowi nadanie nowej nazwy.

Deklaracja:
typedef int  napiecie;

albo:
using napiecie=int;

i teraz:
napiecie nap_progowe;      - to samo co:       int  nap_progowe;

Po co? Możemy w Łatwy sposób zmienić określony typ zmiennych w całym programie
np z int na double




String i vector
std::string    - ułatwia pracę z tekstem
std:vector    - ułatwia pracę z obiektami zebranymi w grupę

using namespace std;         - nie trzeba dopisywac std::



Definicja string:

std::string   solar{"Panel sloneczny"};

std:string  imie;     //pusta 
cin>>imie;


Porównywanie:

if(imie=="Jurek")
{
//...
}



Dodawanie:

string rozkaz;
rozkaz="Naprawic" + imie;             //dodał C-string  do stringa

rozkaz+="na koncu";                       //dodał na końcu na końcu tekstu



Zamiana:
rozkaz=komunikat;



Porównanie alfabetyczne:

if(imie<solar)
  //..;
else
  //..;



Zamiana liczby na stringa:

int a=5;
string  liczba_tekstowo = to_string(a);



Określenie długości:

int dlugosc=imie.size();



                                                             Vektor:
Dyrektywa Vektor:
#include <vector>


Definicja
std::vector<int>                  liczby;
std::vector<std::string>      imiona;               //vector<string>    imiona;


Definicja + wartości:
vector<double>  liczby{3, 10, 100, 1000};
vector<string> imiona{"Janek","Bach"};

indeksujemy od 0


Przykład użycia:

// Program z paragrafu 05_02
 #include <iostream>
 #include <vector>             // 1
 #include <string>
 using namespace std;             // 2
//************************************************************
 int main()
 {
  vector<int> ww { 9,  4,  7,  -6,  2,  7 };       // 3
  cout << "ww[1]= " <<   ww[1]   << endl;        // 4

  int rozmiar = ww.size();         // 5
  cout << "Wektor ww ma elementów " << rozmiar << endl;

  for(unsigned int i = 0 ; i < ww.size() ; ++i) {       // 6
   cout << ww[i] << ", " ;          // 7
  }  cout << endl;

  int b = ww[4] + 500;     // 2 + 500    // 8
  ww[2] = ww[3] * 10;     // –6 * 10    // 9
  cout << "b = " << b << " ww[2] = " << ww[2] << endl;

  cout << "Obecna zawartosc wektora ww: " << endl;
  for(unsigned  int nr = 0 ; nr < ww.size() ; ++nr)      // 10
  {
    cout << "ww[" << nr << "] = " << ww[nr];
    if(ww[nr] == 2) {        // 11
        cout << " <->dwa!";
     }
    cout << endl;
  }
  

    vector<int> m;          // 12
  vector<char> symbole(10);         // 13
  vector<char> litery(12, '.');          // 14
  cout << "Tresc wektora litery:\n";
  for(unsigned int i = 0 ; i < litery.size() ; ++i)  cout << litery[i];
  cout << endl;

  litery[0]   = 'M';          // 15
  litery[6]   = 'B';  litery[10] = 'X';

  for(unsigned int i = 0 ; i < litery.size() ; ++i)  cout << litery[i] ;
  cout << endl;


  // ciąg dalszy programu
  vector<string> fizycy { "G. Galilei", "I. Newton", "A. Einstein" };    // 16

  vector<string> muzycy;           // 17
  cout << "a) muzycy.size() = " << muzycy.size() << endl;

  muzycy.push_back("Chopin");         // 18
  cout << "b) muzycy.size() = " << muzycy.size() << endl;    // 19

  muzycy.push_back("Lutoslawski");
  muzycy.push_back("Debussy");

  for(unsigned int i = 0 ; i < muzycy.size() ; ++i)      // 20
  {
   cout << "muzycy[" << i << "] to: " << muzycy[i] << endl;
  }

  // zamiana treści
  muzycy[1] = "Moniuszko";          // 21
  muzycy[2] = muzycy[0];           // 22
  cout << "Podaj samo nazwisko kompozytora: ";       // 23
  string ulubiony;
  cin >> ulubiony;
  muzycy.push_back(ulubiony);          // 24

  for(unsigned int i = 0 ; i < muzycy.size() ; ++i)    cout << muzycy[i] << ", ";
  cout << endl;
 }



ENUMS
enum Color {
    Red = 0, 
    Green, 
    Blue
};

int foo(int);

int main() {
    Color c = Red;

    foo(c);
}


Tablice
int main() {
    int tabl[] = { 1,2,3,4 };
    int size = sizeof(tabl) / sizeof(int);
}

albo:
#include <array>

int main() {
    std::array<int, 10> array {0,1,2,3,4,5,6,7,8,9};
    array.size(); 
    std::array<int, 10> duplicate; 

    duplicate = array;
}



Konwersja typów

niejawna:
void foo(int);
int main() {
    float z = 5.0f;
    foo(z);
}

jawna:
void foo(int);
int main() {
    float z = 5.0f;
    foo(static_cast<int>(z));
}



Zakresowe FOR

dla:
int main() {
    std::array<int, 10> arr;


iteruje value po kopiach
for(int value: arr) {}

iteruje valuue po referancji (szybsze niz po kopiach)
for(int& value: arr) {}

iteruje po referencji ale nie pozwala jej zmienić
for(const int& value: arr) {}


Ćwiczenie
Wypełnij tablice 100 losowymi elementami i znajdź największy:
#include <iostream>
#include <array>
#include <cstdlib>
using namespace std;

 
int main()
{ 
int maks=0;
 
std::array<int,100>arr;

for(int& value: arr)
{
value=rand()%1000;
}

for(const int& value: arr) 
{
if (value>maks)
  {
  maks=value; 
  }

}

cout<<maks;

}

.
Przykłady tworzenia tablic wraz z inicjalizacjami, Range for nie działa na wskaznikach !!!

#include<iostream>

using namespace std;

int lenght=5;

int tabst[]{1,2,3,4,5};                //inicjalizowanie statycznej tablicy wartosciami
int *array = new int[lenght]();     //inicjalizowanie dynamicznej tablicy zerami c++98
int* tabwsk = new int [3]{1,2,3};   //inicjalizowanie dynamicznej tablicy wartosciami c++11

char *zdaniewsk = "programowanie";  //inicjalizowanie Literałem w stylu C (tablica zakonczone \n)
char zdanie [ ] = "programowanie";  //inicjalizowanie tablicy Literałem w stylu C (zakonczone \n)


int* tab1[3];               // statyczna tablica 3 wskaźników
int* tab2 = new int [3];    // "dynamiczna tablica" 3 int-ów

int** tab3 = new int* [3];  // "dynamiczna tablica" 3 wskaźników


int main ()
{

for (auto aa : zdanie)         //Range For tylko dla niewskaznikow, wskazniki nie maja metody begin
cout<<aa<<endl;

return 0;
}


Przykład tworzenia statycznego obiektu w klasie:


#include<iostream>
#include<string>


struct Human {

    Human(): name("prawda"){std::cout<<"konstruktor1 Human"<<std::endl;}
    Human( std::string a): name(a){std::cout<<"konstruktor2 Human"<<std::endl;}
    std::string name ;

    void drukuj() const noexcept
    {
    std::cout<<name<<std::endl;
    }
};

struct Man  {

Man () : obj("dupa") {std::cout<<"konstruktor Man"<<std::endl;}

Human obj; 

void drukuj()
    {
    obj.drukuj();
    }

};


int main()
{

Man bbb;
bbb.obj.drukuj();

return 0;
}


Jak widać, żeby stworzyć statyczny (nie za pomoca new) obiekt  klasy (tu obj klasy Human tworzony w klasie Man) w innej klasie, trzeba zainicjalizować go na liście inicjalizacyjnej w konstruktorze.









1 Toolchain i preprocesor

Różnica pomiędzy gcc a g++


gcc: GNU C      Compiler
g++: GNU C++ Compiler
The main differences:
  1. gcc will compile: *.c/*.cpp files as C and C++ respectively.
  2. g++ will compile: *.c/*.cpp files but they will all be treated as C++ files.
  3. Also if you use g++ to link the object files it automatically links in the std C++ libraries (gcc does not do this).
  4. gcc compiling C files has fewer predefined macros.
  5. gcc compiling *.cpp and g++ compiling *.c/*.cpp files has a few extra macros.

You can link the std C++ library in gcc by passing -lstdc++ parameter.
There are more differences between 'gcc' and 'g++' than only the standard libraries, so gcc -lstdc++ will still not get you the same behavior as g++

Tabela wersji gcc Link



Instalacja ubuntu WSI (sklep MS) na Windows10:
w Powershel:
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

warto zainstalować HyperTerminal: https://hyper.is/

uruchamianie w terminalu: 
wsl


--------jeśli chcemy połączenie kodu na linuxie z VS Codie na  Windows------
zainstalowac visualcode
ze sciezki z lokalnym linuxem
C:\Users\eblzmrc\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState\rootfs
wejsc na repo i dodac jako working directory projektu w visualu





Instalacja g++ na Debianie:

$ sudo apt-get update
$ sudo apt-get install build-essential manpages-dev

Instalacja nowszych wersji gcc na ubuntu LINK

Instalacja Eclipse na Ubuntui Link 


(Fedora, RedHat,CentOs)
# yum groupinstall 'Development Tools'



g++ demo2.Cpp -o demo2
## or use the following syntax ##
make demo2
To run this program, type:
./demo2

Program
#include <iostream>
using namespace std;
int main(void) {
 cout << "It's me, your first program.";
 return 0;
}


kompilowanie w określonym standardzie
$   g++    test.cpp    -std=c++ 11

inne standardy:

  • -std=c++98, or -std=gnu++98 (C++98 with GNU extensions)
  • -std=c++11, or -std=gnu++11 (C++11 with GNU extensions)
  • -std=c++14, or -std=gnu++14 (C++14 with GNU extensions), default mode for GCC 6.1 and above.
  • -std=c++17, or -std=gnu++17 (C++17 with GNU extensions), experimental.
  • -std=c++2a, or -std=gnu++2a (C++2a with GNU extensions), experimental.



wygeneruje plik uruchamialny - uruchamiać  ./a.out
a.out



Kompilatory online:

Coliru⁸ - uses GCC 8.1.0 (as of July 2018), offers link sharing and a basic text editor, it’s
simple but very effective.
• Wandbox⁹ - it offers a lot of compilers - for example, most of Clang and GCC versions
- and also you can use boost libraries. Also offers link sharing.
• Compiler Explorer¹⁰ - shows the compiler output from your code! Has many compilers
to pick from.
• CppBench¹¹ - run a simple C++ performance tests (using google benchmark library).
• C++ Insights¹² - it’s a Clang-based tool which does a source to source transformation.
It shows how the compiler sees the code, for example by expanding lambdas, auto,
structured bindings or range-based for loops.





Jeśli rozbite na kilka plików:

Główny plik main.cpp który uruchamia funkcję foo();
#include "test.h"

int main() {
    void foo();
}

Plik test.h  który zawiera prototyp funkcji foo() (deklaracja - zakończona średnikiem )
void foo();

Plik test.cpp który zawiera definicję (ciało) funkcji foo()
#include "test.h"

void foo() { 
    // ... 
}

Jak kompilować
-o  tworzy wykonywalny (-o2 poziom optymalizacji) albo z obiektów albo od razu z cpp

g++   test.cpp   main.cpp   -o   program


ewentualnie po kolei:   Sss

-c  tworzy obiekt *.o

g++  -c  test.cpp  -o  test.o
g++  -c  main.cpp -o main.o
i linkujemy:
g++  test.o  main.o  -o  program


$ file program
dostajemy informacje o pliku (linux)

Makefile - patrz C
Link



CMAKE

1) stwórz:

CMakeLists.txt


cmake_minimum_required(VERSION 3.0)

set(CMAKE_BUILD_TYPE Debug)


project(zad3)

add_executable(
   zad3 
   zad3.c
)

zad3 - nazwa pliku uruchamialnego
zad3.c - plik z programem
dodaj kolejne plik *.c    i   *.h


2) polecenie

$ cmake .             (kropka po spacji !!!)

tworzy plik MakeFile


3) polecenie

$ make

plik uruchamialny "zad3" stworzony


Przykład tworzenia plików




1
2
3
4
5
6
7
8
9
10
11
12
13
// galik.h
#ifndef _GALIK_H
#define _GALIK_H

#include <string>

namespace galik {

void func(); // prototypes

} // namespace galik

#endif // _GALIK_H 


1
2
3
4
5
6
7
8
9
10
11
12
// galik.cpp
#include "galik.h"

namespace galik {

void func() // definition
{
 // do stuff
}

} // namespace galik



How do I generate symbolic information for gdb and warning messages?

The syntax is as follows C compiler:
cc -g -Wall input.c -o executable
The syntax is as follows C++ compiler:
g++ -g -Wall input.C -o executable

How do I generate optimized code on a Linux machine?

The syntax is as follows C compiler:
cc -O input.c -o executable
The syntax is as follows C++ compiler:
g++ -O -Wall input.C -o executable

How do I compile a C program that uses math functions?

The syntax is as follows when need pass the -lm option with gcc to link with the math libraries:
cc myth1.c -o executable -lm

How do I compile a C++ program that uses Xlib graphics functions?

The syntax is as follows when need pass the -lX11 option with gcc to link with the Xlib libraries:
g++ fireworks.C -o executable -lX11

How do I compile a program with multiple source files?

The syntax is as follows if the source code is in several files (such as light.c, sky.c, fireworks.c):
cc light.c sky.c fireworks.c -o executable
C++ syntax is as follows if the source code is in several files:
g++ ac.C bc.C file3.C -o my-program-name

The Standard C++ library consists of 53 headers. Of these 53 headers, 13 constitute
the Standard Template Library, or STL. These are indicated below with the
notation (STL):

<algorithm> (page 249) — (STL) for defining numerous templates that
implement useful algorithms
<bitset> (page 54) — for defining a template class that administers sets of bits
<complex> (page 61) — for defining a template class that supports complex
arithmetic
<deque> (page 274) — (STL) for defining a template class that implements a
deque container
<exception> (page 74) — for defining several functions that control exception
handling
<fstream> (page 76) — for defining several iostreams template classes that
manipulate exteral files
<functional> (page 282) — (STL) for defining several templates that help
construct predicates for the templates defined in <algorithm> (page 249) and
<numeric> (page 345)
<iomanip> (page 85) — for declaring several iostreams manipulators that take
an argument
<ios> (page 86) — for defining the template class that serves as the base for
many iostreams classes
<iosfwd> (page 102) — for declaring several iostreams template classes before
they are necessarily defined
<iostream> (page 103) — for declaring the iostreams objects that manipulate the
standard streams
<istream> (page 105) — for defining the template class that performs
extractions
<iterator> (page 293) — (STL) for defining several templates that help define
and manipulate iterators
<limits> (page 114) — for testing numeric type properties
<list> (page 310) — (STL) for defining a template class that implements a list
container
<locale> (page 119) — for defining several classes and templates that control
locale-specific behavior, as in the iostreams classes
<map> (page 320) — (STL) for defining template classes that implement
associative containers that map keys to values
<memory> (page 336) — (STL) for defining several templates that allocate and
free storage for various container classes
<new> (page 164) — for declaring several functions that allocate and free
storage
<numeric> (page 345) — (STL) for defining several templates that implement
useful numeric functions
<ostream> (page 168) — for defining the template class that performs insertions
<queue> (page 347) — (STL) for defining a template class that implements a
queue container
<set> (page 353) — (STL) for defining template classes that implement
associative containers
<sstream> (page 176) — for defining several iostreams template classes that
manipulate string containers
<stack> (page 368) — (STL) for defining a template class that implements a
stack container
<stdexcept> (page 184) — for defining several classes useful for reporting
exceptions
<streambuf> (page 185) — for defining template classes that buffer iostreams
operations
<string> (page 195) — for defining a template class that implements a string
container
<strstream> (page 217) — for defining several iostreams classes that manipulate
in-memory character sequences
<typeinfo> (page 224) — for defining class type_info, the result of the typeid
operator
<unordered_map> (page 371) — (STL) for defining template classes that
implement unordered associative containers that map keys to values
<unordered_set> (page 386) — (STL) for defining template classes that
implement unordered associative containers
<utility> (page 400) — (STL) for defining several templates of general utility
<valarray> (page 225) — for defining several classes and template classes that
support value-oriented arrays
<vector> (page 403) — (STL) for defining a template class that implements a
vector container
Link

WikiLink

Standard Library header files Link

PUB

PR

Csh

Google C++ Style Guide

Google protocol-buffers 

Program studiów Informatycznych

Bartłomiej Filipek book:     C++17 in Detail  book 

MeetUp:                              C++ User Group Krakow

C++ Team Blog MS
            ciekawe artykuły z bloga MS:
            C++ with Visual Studio 2019 and Windows Subsystem for Linux (WSL)
            Linux Development with C++ in Visual Studio 2019: WSL, ASan for Linux, Separation of Build and Debug
            Visual Studio Code C/C++ extension: May 2019 Update
            Using VS Code for C++ development with containers