sudo apt-get install -y root-system # librairie Root du Cernsudo apt-get install -y emacs emacs-goodies-el global clang auto-complete-el cscope-el # logiciel pour recherche de fonctions etcsudo apt-get install -y libarmadillo-dev # C++ linear algebra librarysudo apt-get install -y libboost-devsudo apt-get install -y libboost-all-dev
brew install armadillobrew install rootbrew install emacs-clang-complete-asyncbrew cask install emacsbrew install boostbrew install xfigbrew install fig2dev
#include <iostream>using namespace std;int main(){cout << "Bonjour!" << endl;}et sauvegarder ce fichier qui contient le code C++ de votre programme. (Observer les raccourcis clavier proposés par emacs dans ses menus pour toutes ces commandes: par exemple “Save : C-x C-s” signifie que les touches Ctrl avec x puis Ctrl avec s. “Shell Command M-!” signifie les touches Alt avec !).
all:et sauvegarder ce fichier qui contient les instructions pour compiler votre programme. Attention: au début de la deuxième ligne rajouter un espace de tabulation avant g++. Remarque: on peut basculer d’un fichier à l’autre dans emacs par le menu “Buffers” ou par le clavier avec C-x C- .
g++ projet1.cc -o projet1 -std=c++11 -O3 -Wall -lm
le désavantage est que pour corriger l’erreur il faut soit même se placer sur la ligne indiquée.Une autre possibilité pour compiler est d’écrire la commande make all dans le terminal qui a pour effet d’exécuter le fichier Makefile.
#include <iostream>using namespace std;/* ==============Programme principal===================*/int main(){
int a,b; // déclaration des objets a et b de la classe inta=1; // affectation: a prend la valeur 1b=a+1; // affectation b prend la valeur 2int c; // déclaration de l objet c de classe intc=a+b; // affectation: c prend la valeur a+b c’est à dire 3// affichage à l’écran:cout << "la somme de " << a << " et " << b << " vaut " << c <<endl;}
#include <iostream>using namespace std;int main(){
int a,b; // déclaration des objets a et b de la classe intcout <<"Quelle est la valeur de a ? "<<flush;cin >> a; // lire a au clavier, attendre returncout <<"Quelle est la valeur de b? "<<flush;cin >> b; // entrer b au clavier puis returnint c; // déclaration de la objet c de la classe intc = a + b; // affectation: c prend la valeur a+b// affichage à l’écran:cout <<"la somme de "<<a<<" et "<<b<<" vaut "<<c<<endl ;}
Déclaration: classe objet; | signification | Limites |
int a; | nombre entier | -2147483648 à 2147483647 |
double d; | nombre réel double précision | à près |
char e; | caractère | |
bool v; | booléen: vrai (true) ou faux (false) | |
char * t; | chaîne de caractères |
#include <iostream>using namespace std;main (){int i = 0;double x = 1.23;double x1(3.4),x2(6); // equivalent a x1=3.4double y(x1), y2 = x2;char Mon_caractere_prefere = ’X’;const char * texte = "que dire de plus?";char c = texte[0]; // premier caractereauto z = x + 2;{double x=5;}}
#include <iostream>using namespace std;#include <math.h>#include <iomanip>//..................main (){double c = M_PI;cout<<setprecision(3)<<c<<endl;}
3.14
#include <iostream>using namespace std;//......main (){int a=7, b=2;double c=7.;cout<<"7/2 = "<<a/b<<" = "<<7/2<<endl;cout<<"7./2 = "<<c/b<<" = "<<7./2<<" = "<<(double)a/b<<endl;cout<<"Le quotient de 7/2 = "<<7/2<<" Le reste de 7/2 est r= "<<7%2<<endl;}
7/2 = 3 = 37./2 = 3.5 = 3.5 = 3.5Le quotient de 7/2 = 3 Le reste de 7/2 est r= 1
#include <iostream>using namespace std;#include <time.h>#include <stdlib.h>main (){srand(time(NULL)); // initialise le hasard.(faire cela une seule fois en debut de programme)int N = 100;int p = rand()%(N+1); // -> entier aléatoire entre 0 et N compris.cout<<" p="<<p<<endl;}
#include <iostream>#include <string>using namespace std;main (){
string texte1 = "J’aime le café";cout << texte1<<endl;string texte2 = texte1 + " sans sucre";cout << texte2<<endl;cout<<"Le premier caractère est du texte précédent est: "<<texte2[0]<<endl;}
J’aime le caféJ’aime le café sans sucreLe premier caractère du texte précédent est:J
J’aime le café sans sucreLe troisième caractère du texte précédent est:a
#include <iostream>using namespace std;#include <string>#include <sstream>//.....main (){//..... Conversion number to string.int d=7; // chiffrestring S = to_string(d);cout<<"d="<<d<<" S="<<S<<endl;//..... Conversion string to number.string s5 = "3"; // chaine contenant des chiffresint i5 = stoi(s5);string s6 = "3.14"; // chaine contenant des chiffresdouble d6 = stod(s6);cout<<"i5="<<i5<<" d6="<<d6<<endl;}
#include <iostream>using namespace std;#include <complex>typedef complex<double> Complex;main (){
Complex I(0,1); // on définit le nombre Icout<<"I.I="<<I*I<<endl;Complex a=2.+I*4., b=3.-2.*I;Complex c=a+b, d=a*b;cout<<" a="<<a<<" b="<<b<<endl;cout<<" a+b="<<c<<" a*b="<<d<<endl;cout<<" real(a)="<<a.real()<<" norme(a)="<<abs(a)<<endl;}
I.I=(-1,0)a=(2,4) b=(3,-2)a+b=(5,2) a*b=(14,8)real(a)=2 norme(a)=4.47214
#include <iostream>using namespace std;#include <vector>main (){vector<int> L; // liste vide qui contiendra des objets de type intL.push_back(2); //rajoute l’element 2 a la fin de la listeL.push_back(3); // rajoute 3 a la fin de la listeL.push_back(5);cout<<"La liste a la taille :"<<L.size()<<endl;cout<<"Ses elements sont: "<<L[0]<<" , "<<L[1]<<" , "<<L[2]<<endl;}
#include <iostream>using namespace std;#include <vector>#include <algorithm>main (){//--- recherche la position de l’element maximal de la listevector<int> L={5,7,3,12,34,6}; // on initialise une liste d’entierscout<<"Le premier élément de la liste est "<<L[0]<<endl;int p = max_element(L.begin(),L.end())-L.begin(); //renvoit la position du maximum dans l’ordre (0,1,2..)cout<<"L’élement le plus grand est "<<L[p]<<endl;cout<<"Il est à la position "<<p<<endl;//--- cherche la premiere/derniere position d’un element avec find() / rfind()int e = 6;int p2 = find(L.begin(), L.end(), e) - L.begin(); // cherche la position de l’element eif(p2<L.size())cout<<"Le "<<e<<" est à la position "<<p2<<endl;elsecout<<"Le "<<e<<" n’est pas dans la liste."<<endl;}
Le premier élément de la liste est 5L’élement le plus grand est 34Il est à la position 4Le 6 est à la position 5
#include <iostream>using namespace std;#include <armadillo>using namespace arma;main (){Col<int> V("1 2 3"); // vecteur colonne d’entierscout<<"V="<<endl<<V<<endl;Mat<int> M("3 2 1; 4 5 0");// matrice d’entierscout<<"M="<<endl<<M<<endl;Col<int> W = M * V; // calcule le produitcout<<"M*V="<<endl<<W<<endl;cout<<"element de matrice M(0,0)="<<M(0,0)<<endl;}
V= 123M= 3 2 14 5 0M*V= 1014element de matrice M(0,0)=3
A = 1 10 1B = 1 01 1A*B = 2 11 1
#include <iostream>using namespace std;#include <armadillo>using namespace arma;main (){//---- initialisations//... vec est equivalent a Col<double>vec V1 = randu<vec>(5); // vecteur colonne de 10 composantes aleatoires unif. dans [0,1]cout<<"V1="<<endl<<V1<<endl;//... mat est equivalent a Mat<double>mat M1;M1.zeros(3,3); // matrice 3*3 remplie de zeroscout<<"M1="<<endl<<M1<<endl;//----- conversions de typesvector<double> V2 = conv_to<vector<double>>::from(V1); // V1 -> V2cout<<"V2[0]="<<V2[0]<<endl;}
sudo apt-get install -y xorg-devsudo apt-get install x-devsudo apt-get install root-system
-I/usr/include/root `root-config --cflags` `root-config --libs` `root-config --glibs`
-I/usr/include/root
`root-config --cflags` `root-config --libs` `root-config --glibs`
#include <TApplication.h> // (A)#include <TCanvas.h> //(B)#include <TEllipse.h> // (C)//------ fonction main (A) --------------------int main(){TApplication theApp("App", nullptr, nullptr); // (A)TCanvas c("c","fenetre",400,400); // (B) objet fenetre graphique. Taille en pixelsc.Range(0,0,5,5); // coordonnees de la fenetre c: x:0-5, y:0-5 (optionnel, par defaut ce sera 0-1)//------ dessin d’une ellipse dans la fenetre c (C) -------TEllipse e(2,3,1); // on precise le centre (x=2,y=3) et le rayon=1e.Draw(); // dessine l’ellipse
c.Update(); //(B) Montre le dessintheApp.Run(); // (A) garde la fenetre ouverte et permet a l’utilisateur d’interagir.}
e.SetFillColor(kBlue);e.SetFillStyle(3025); // motif en carreaux
#include <TApplication.h>#include <TCanvas.h>#include <TLine.h>#include <TEllipse.h>#include <TMarker.h>#include <TBox.h>#include <TText.h>int main(){TApplication theApp("App", nullptr, nullptr);//.. La fenetreTCanvas c("titre","titre",10,10,400,400); //position x,y sur l’ecran et taille X,Y en pixelsc.Range(0,0,1,1); // xmin,ymin,xmax,ymax, systeme de coordonnees//.. une ligne bleueTLine l(0.1,0.5,0.3,0.9); // x1,y1,x2,y2.l.SetLineColor(kBlue); // bleul.Draw();//.. Une Ellipse (ou cercle)TEllipse e(0.2,0.3,0.1); // (centre (x,y) et rayon re.Draw();//.. Un pointTMarker m(0.3,0.4,8); // (x,y) et 6 ou 8: forme du Markerm.SetMarkerColor(kPink);m.Draw();//.. Un rectangle vertTBox p(0.15,0.6,0.25,0.7); // on precise les coins bas-gauche (x1,y1) et haut droit (x2,y2) :p.SetFillColor(kGreen);p.Draw();//.. Du texteTText texte(0.2,0.2,"un petit texte"); // position x,ytexte.Draw();c.Update(); // Montre le dessintheApp.Run(); // garde la fenetre ouverte et permet a l’utilisateur d’interagir.}
#include <iostream>using namespace std;main (){cout<<”abcdefghij”<<endl;cout<<”abc\def\ghij”\<<endl;}
abcdefghijabcdefghij
#include <iostream>using namespace std;#include <typeinfo>main (){auto a=’A’;cout << typeid(a).name() <<endl;auto x=3.14;cout << typeid(x).name() <<endl;auto s="ABC";cout << typeid(s).name() <<endl;}
cdPKc
#include <iostream>using namespace std;main (){int b=1;cout<<" b="<<b<<endl;b++; // equivalent a b=b+1cout<<" b="<<b<<endl;b-- ; // equivalent a b=b-1cout<<" b="<<b<<endl;}
#include <iostream>using namespace std;#include <string>int main(){//----- find() ---------string s1 = "ab&-e&-f";cout<<"chaine s1="<<s1<<endl;auto pos1 = s1.find("&-"); // recherche premiere occurence de "&-" dans s1if(pos1!=string::npos)cout<<"Dans la chaine s1, \"&-\" se trouve a la position pos1 = "<<pos1<<endl;auto pos2 = s1.find("toto");if(pos2==string::npos)cout<<"Dans la chaine s1, \"toto\" n’a pas été trouvé"<<endl;//----- substr() ---------string s2 = s1.substr(0, s1.find("&-")); // extrait sous chaine entre le debut (indice 0) la premiere occurence de "&-"string s3 = s1.substr(0, s1.rfind("&-")); // extrait sous chaine entre le debut (indice 0) et la derniere occurence de "&-"string s7 = s1.substr(s1.find("&-")); // extrait sous chaine entre la premiere occurence de "&-" et la finstring s4 = s1; // copies4.erase(0,2); // a la position 0, enleve 2 caracteresstring s5 = s1; // copies5.erase(s1.size()-2,2); // enleve les 2 caracteres de la finstring s6 = s1; // copieint p;while(((p=s6.find("-"))>=0) && (p<=s6.size()))s6.replace(p,1,"*"); // remplace tous les "-" par "*"cout<<"s2="<<s2<<endl<<"s3="<<s3<<endl<<"s7="<<s7<<endl<<"s4="<<s4<<endl<<"s5="<<s5<<endl<<"s6="<<s6<<endl;}
chaine s1=ab&-e&-fDans la chaine s1, "&-" se trouve a la position pos1 = 2Dans la chaine s1, "toto" n’a pas été trouvés2=abs3=ab&-es7=&-e&-fs4=&-e&-fs5=ab&-e&s6=ab&*e&*f
#include <iostream>using namespace std;#include <string>#include <sstream>//.....main (){//..... Conversion chiffre -> string.int c=7; // chiffreostringstream os;os<<"resultat :"<<c; // on concatene du texte et le chiffrestring s = os.str(); // convertit os en stringcout<<"s= "<<s<<endl; // affichage pour verifier//..... Conversion string -> chiffres.string s2 = "3 4"; // chaine contenant des chiffresistringstream is;is.str(s2); // convertit chaine s2 en isint a,b;is>>a; // extrait le premier chiffre trouve dans isis>>b; // extrait chiffre de iscout<<"s2="<<s2<<endl;cout<<"a="<<a<<" b="<<b<<endl; // affichage pour verifier}
#include <iostream>using namespace std;#include <string>#include <bitset>//.....main (){//... Conversion entier -> string (base 2)int n4=117;string s4 = bitset<8>(n4).to_string(); // nombre -> string (base 2)cout<<"n4="<<n4<<" s4="<<s4<<endl;//.. Conversion string (nombre en base 2) -> entierstring s5="10011";unsigned long n5 = bitset<8>(s5).to_ulong();cout<<"s5="<<s5<<" n5="<<n5<<endl;}
n4=117 s4=01110101s5=10011 n5=19
#include <iostream>using namespace std;#include <bitset>main (){//... Declaration et Affichage en base deux:int A=0b1001; // declaration en base 2 (prefixe 0b)cout<<" A="<<A<<" en binaire = "<<bitset<8>(A)<<endl;cout<<" Nombre de bits non nuls de A="<< bitset<8>(A).count()<<endl;//.. decalages de bitsint b= A<<4; // equivalent: b= A * pow(2,4)cout<<" b ="<<b<<" = "<< bitset<8>(b)<<endl;int c = b>>3; // equivalent: c= b / pow(2,3)cout<<" c ="<<c<<" = "<< bitset<8>(c)<<endl;//.. operations bits a bitsint B = 0b1;int d = A | B; // ou inclusif bit a bit cad 1|1 donne 1int e = A ^ B; // ou exclusif bit a bit cad 1^1 donne 0int f = A & B; // et bit a bitint g = ~A; // non A, inversion des bitscout<<" B="<<B<<" = "<<bitset<4>(B)<<endl;cout<<" A|B = "<<d<<" = "<<bitset<4>(d)<<endl;cout<<" A^B = "<<e<<" = "<<bitset<4>(e)<<endl;cout<<" A&B = "<<f<<" = "<<bitset<4>(f)<<endl;cout<<" ~A = "<<g<<" = "<<bitset<8>(g)<<endl;}
a=0xFA;cout<<a<<endl;cout<<hex<<a<<endl; // pour afficher en base 16.
#include <iostream>using namespace std;#include <tuple>main (){//... constructiontuple<int,char> o1(10,’x’); // creation d’un objet constitué d’un entier 10 et un caractère xauto o2 = make_tuple ("test", 3.1, 14, ’y’); // construction sans preciser les types//... lecture des elementsint a = get<0>(o1); // on extrait le premier element (position 0)cout<<"a="<<a<<endl;int b; char c;tie (b,c) = o1; // extraits les elements de o1cout<<"b="<<b<<" c="<<c<<endl;int d;tie (ignore, ignore, d, ignore) = o2; // extrait certains elements de o2cout<<"d="<<d<<endl;//..... ecriture d’elementsget<0>(o1) = 100; // on remplace l’element 0 de o1cout<<"o1[0]="<<get<0>(o1)<<endl;//.. concatenation de tuplesauto o3 = tuple_cat(o1,o2);cout<<"o3[5]="<<get<5>(o3)<<endl;}
a=10b=10 c=xd=14o1[0]=100o3[5]=y
#include <iostream>using namespace std;#include <armadillo>using namespace arma;main (){int N=3;mat M = randu<mat>(N,N); // elements au hasardM= 0.5*(M + trans(M)); // la rend symetriquevec val_p;mat vec_p;eig_sym( val_p, vec_p, M);cout<<"Matrice symetrique M="<<endl<<M<<endl;cout<<"valeurs propres="<<endl<<val_p<<endl;cout<<"vecteurs propres en colonnes="<<endl<<vec_p<<endl;cout<<"Verification M v0-l0 *v0 = 0 ? on trouve: "<<endl<<M*vec_p.col(0) - val_p(0) *vec_p.col(0) <<endl;}
#include <iostream>using namespace std;#include <armadillo>using namespace arma;main (){int N=3;cx_mat M = randu<cx_mat>(N,N); // elements au hasardM= 0.5*(M + trans(M)); // la rend symetriquevec val_p;cx_mat vec_p;eig_sym( val_p, vec_p, M);cout<<"Matrice symetrique M="<<endl<<M<<endl;cout<<"valeurs propres="<<endl<<val_p<<endl;cout<<"vecteurs propres en colonnes="<<endl<<vec_p<<endl;cout<<"Verification M v0-l0 *v0 = 0 ? on trouve: "<<endl<<M*vec_p.col(0) - val_p(0) *vec_p.col(0) <<endl;}
#include <iostream>using namespace std;#include <armadillo>using namespace arma;main (){int N=3;cx_mat M = randu<cx_mat>(N,N); // elements au hasardcx_vec val_p;cx_mat vec_p;eig_gen( val_p, vec_p, M); // diagonalise//... ordonne les valeurs propres (et vect p) par module decroissantuvec indices = sort_index(abs(val_p),"descend"); // liste des indices, "ascend" or "descend"val_p=val_p(indices); // vecteur ordonnévect_p=vect_p.cols(indices); // vecteur ordonnécout<<"Matrice complexe M="<<endl<<M<<endl;cout<<"valeurs propres="<<endl<<val_p<<endl;cout<<"vecteurs propres en colonnes="<<endl<<vec_p<<endl;cout<<"Verification: M v0-l0 *v0 = 0 ? on trouve: "<<endl<<M*vec_p.col(0) - val_p(0) *vec_p.col(0) <<endl;}
#include <iostream>using namespace std;#include <armadillo>using namespace arma;main (){int N=10;//---- creation de matrice sparsesp_mat A = sprandu<sp_mat>(N, N, 0.1); // matrice sparse N*N aleatoire avec une densite 0.1 d’elements non nulssp_mat B(N,N);B(1,2)=1;cout<<"Matrice B="<<endl<<B<<endl; // affiche que les elements non nulssp_mat M = A.t()*A;M(1,1)=1;cout<<"Matrice symetrique M="<<endl<<M<<endl; // affiche que les elements non nuls//---------- diagonalisationvec val_p;mat vec_p;int n=5;eigs_sym(val_p, vec_p, M, n, "lm"); // chercher les n premieres eigenvalues/eigenvectors avec option: "lm": les + grandes (default), ou "sm": les + petites.cout<<"valeurs propres="<<endl<<val_p<<endl;cout<<"vecteurs propres en colonnes="<<endl<<vec_p<<endl;cout<<"Verification M v0-l0 *v0 = 0 ? on trouve: "<<endl<<M*vec_p.col(0) - val_p(0) *vec_p.col(0) <<endl;}
#include <iostream>using namespace std;int main(){for(int i=2; i<=8; i=i+2)
{int j=i*i;cout <<i << "\t "<<j <<endl;}}
#include <iostream>using namespace std;#include <vector>int main(){vector<int> L={5,7,3,12}; // une listefor(auto x:L) // la variable x parcourt la liste Lcout<<x+1<<",";}
6,8,4,13,
#include <iostream>using namespace std;int main(){for(int i=2; i<=8; i=i+2)cout<<"i="<<i<<endl; // pas d’accoladesfor(int i=2; i<=8; i=i+2){ // accolade de debut de blocint j=i*i;cout<<"i="<<i << "\t "<<"j="<<j <<endl;} //accolade de fin}
i=2i=4i=6i=8i=2 j=4i=4 j=16i=6 j=36i=8 j=64
Signification | symbole |
supérieur à | > |
inférieur à | < |
supérieur ou égal à | >= |
inférieur ou égal à | <= |
égal à | == |
différent de | != |
Signification | symbole |
et | && |
ou | || |
non | ! |
#include <iostream>using namespace std;main (){int a=1, b=2, c=3;if( ((a <= b ) || (b >=c) ) && (a<c) )cout<<"Yes"<<endl;elsecout<<"No"<<endl;}
#include<iostream>using namespace std;main( ){int MAX(11);int i(1),j;do{j=i*i;cout<<i<<"\t "<<j<<endl;i=i+1; // Ne pas oublier l’incrémentation}while(i<MAX); //condition}
#include <iostream>using namespace std;main ( ){int max=11;int i=1, j;while(i<max) // condition
{j=i*i;cout<<i<<"\t"<<j<<endl;i=i+1; // ne pas oublier l’incrémentation}; // ne pas oublier le point virgule}
#include<iostream>using namespace std;int main(){for(int i=1; i<=10; i=i+1){if (i==4)cout<<"i= "<<i<<endl;}}
#include<iostream>using namespace std;int main(){for(int i=1; i<=10; i=i+1){if (i == 4)cout<<"i="<<i<<endl;else if(i==5)cout<<"2*i= "<<2*i<<endl;elsecout<<"."<<endl;}}
#include<iostream>using namespace std;int main(){int i=1;for(i=1; i<5; i=i+1);cout<<i;}
#include <iostream>using namespace std;int main(){for(int i=2;i<=10;i=i+2)
{if (i==4)
continue; // on passe au suivant.if (i==8)
break; // on sort de la boucleint j=i*i;cout<<i << "\t "<<j <<endl;}}
#include<iostream>using namespace std;//======declaration de la fonction carre ===================================double carre(int i){double j=i*i;return j; //on renvoie le résultat au programme principal}//===declaration de la fonction principale =====int main(){int x;cout<<"entrer x "<<endl;cin>>x;double y=carre(x); // appel de la fonction carrecout<<"Le carré de "<<x<<" est "<<y<<endl;}
entrer x2le carré de 2 est 4
#include <iostream>using namespace std;//!========declaration de la fonction carre=============void carre(int i){int j=i*i; // declaration d’un objet localcout<<"le carré de "<<i<<" est "<<j<<endl;}//!====declaration de la fonction principale =====================int main(){int x;cout<<" entrer x "<<endl;cin>>x;carre(x); // appel de la fonction carre}
entrer x2le carré de 2 est 4
#include<iostream>using namespace std;//====== fonction permute ==================void permute(int& i,int& j) // passage des parametres par reference{
int t=i; // stockage temporairei=j;j=t;}//======== fonction main ===================int main(){
int a=10, b=5;cout<<a<<" "<<b<<endl;permute(a,b);cout<<a<<" "<<b<<endl;}
10 55 10
#include<iostream>using namespace std;//-------------------------------------------void f(int i){cout<<"fonction 1 appelée"<<endl;cout<<" paramètre = "<<i<<endl;}//-------------------------------------------void f(char *s,int i){cout<<"fonction 2 appelée"<<endl;cout<<" paramètre = "<< s <<endl;cout<<" paramètre = "<< i <<endl;}//---------------------------------------------int main(){f(10);f("Chaîne ",4);}
long a=5;long b = factorielle(a);cout<<" a="<<a<<" a!="<<b<<endl;
afin qu’il affiche comme résultat:a= 5 a!=120
int i;
int i=2; // déclare l’objet i et affecte la valeur 2int *p; // déclaration du pointeur pp=&i; // p devient l’adresse de i
cout<<i;
cout<<(*p);
i=5;
(*p)=5;
#include <iostream>using namespace std;int main(int argc, char *argv[]){cout<<"nombres de parametres argc ="<<argc<<endl;cout<<" Ce sont:"<<endl;for(int i=0;i<argc; i++){cout<<"argv["<<i<<"] = "<<argv[i]<<endl;}return 0; // renvoit l’entier 0 (signifie habituellement 0K)}
(*p)=1;
p[0]=1;
*(p+1)=2;
p[1]=2;
delete [ ] p; // on libere les cases mémoire
#include<iostream>using namespace std;int main(){int n;cout <<"entrez nbre d’objets n >=0 ?"<< flush;cin >> n;double *p; //on déclare le pointeur pp=new double[n]; // on réserve n cases mémoire de la classe double//--- remplissage des cases memoiresfor(int i=0; i<n; i++)p[i]=2*i;//---- affichagefor(int i=0; i<n; i++)cout<<" p["<<i<<"]="<<p[i]<<endl;delete [ ] p; // on libere les cases mémoire}
double p[6]; // creation de 6 cases mémoires de type double, numérotées de 0 à 5.p[1] = 3.14; // on écrit dans la case 1.Il s’agit d’une allocation de mémoire dite statique (non dynamique) car le nombre de case est fixé à la compilation, et ne peut être variable. On peut aussi déclarer et initialiser en même temps:double p[6] = {1, 3.14, 3., 0.};
int *p;p=new int; // on réserve une case mémoire de classe int.(*p)=1;delete p; // pour libérer la place mémoire
char *chaine = “toto”;
qui déclare chaine comme étant un pointeur sur caractère, pointant sur les 4 caractères toto.
entrez n? 3entrez p[0] ? unentrez p[1] ? petitentrez p[2] ? programmep[0] =unp[1] =petitp[2] =programme
#include <TApplication.h>#include <TEllipse.h>#include <TCanvas.h>#include <vector>using namespace std;int main(){TApplication theApp("App", nullptr, nullptr);TCanvas c( "c","fenetre",400,400); // on precise la taille en pixelsc.Range(-2,-2,8,2); // coordonnees de la fenetre//-------------vector<TEllipse> tab_e(3); // liste de 3 ellipsesfor (int i=0; i<3; i++)
{tab_e[i].SetX1(3*i); // coord x du centretab_e[i].SetY1(0); //coord y du centretab_e[i].SetR1(1); // rayon selon xtab_e[i].SetR2(1); // rayon selon ytab_e[i].SetFillColor(kWhite);tab_e[i].Draw(); // dessin}//-------------c.Update();theApp.Run();}
tab_e.erase(tab_e.begin()+1);
Rajouter cette ligne au bon endroit, dans le programme précédent et observer le résultat.
#include <TApplication.h>#include <TEllipse.h>#include <TCanvas.h>#include <vector>using namespace std;int main(){TApplication theApp("App", nullptr, nullptr);TCanvas c( "c","fenetre",400,400); // on precise la taille en pixelsc.Range(-2,-2,8,2); // coordonnees de la fenetre//-------------TEllipse *pe; // crée un pointeur sur TEllipsefor (int i=0;i<3;i++){
pe= new TEllipse(3*i,0,1); // pe pointe sur une ellipse crée en position x=3*i, y=0, rayon 1pe->Draw(); // dessin}//-------------c.Update();theApp.Run();}
#include <iostream>using namespace std;#include <math.h>// ===============déclaration de la classe ===============class Vect{public:double x,y,z;};//====== Programme principal =======================int main(){Vect v; // declarationv.x=1; v.y=2; v.z=3;cout << "composante v.y = " << v.y << endl;}
composante v.y = 2
#include <iostream>using namespace std;#include <math.h>// ===============déclaration de la classe ===============class Vect{public://---- variables membresdouble x,y,z;//-- le constructeur---Vect(){x=0; y=0; z=0;cout << "vecteur construit... " << endl;}//-- le destructeur---~Vect(){cout << "vecteur détruit.... " << endl;}//--la fonction Norme---double Norme(){double n=0;n=x*x+y*y+z*z;return sqrt(n);}};//====== Programme principal =======================int main(){Vect v; // declarationv.x=1; v.y=2; v.z=3;cout << "Norme = " << v.Norme() << endl;}
//====== Programme principal =======================int main(){Vect *w = new Vect(); // declarationw->x=0; w->y=3; w->z=4;cout << "Norme de w = " << w->Norme() << endl;}
#include <iostream>using namespace std;#include <fstream> // utilisation des fichiersint main(){ofstream f("hector.txt"); // ouvre le fichier hector.txt pour y ecrire. On lui associe l’objet: ff<<3.1514<<endl; // permet d’ecrire dans le fichier.f.close(); // fermeture du fichier f}
#include<iostream>using namespace std;#include<fstream> // utilisation des fichiersint main(){
ifstream g("hector.txt");// ouvre un nouveau fichier en lecture. On lui associe l’objet: gdouble x;g>>x; //on lit ce qu’il y a au début du fichier, et on le copie dans l’objet xcout<<x<<endl; // on écrit à l’écran le contenu de xg.close(); // fermeture du fichier g}
if(g.good())cout<<x<<endl;
En effet g.good() renvoit true si la lecture précédente s’est bien faite.
#include <iostream>using namespace std;#include <string>#include <fstream>int main(){//... ecrit des lignes de texte dans un fichierofstream f("test.txt");f<<"ligne1: abc"<<endl;f<<"ligne2: def"<<endl;f.close();//... ouvre le fichier en lectureifstream g("test.txt");string l;while(g.good()){getline(g, l);// -> l. copie la ligne dans l (sans le code retour a la ligne)cout<<l<<endl; // affiche ligne l}g.clear(); // remet les indicateurs à zero pour continuer la recherche.//....g.seekg(0, g.beg); // se place au debut du fichier (begining + 0)int p;p=g.tellg(); // -> position p dans le fichiercout<<"p="<<p<<endl;char c;for(int i=0; i<=5; i++){g.get(c); // -> c. Lit caracterecout<<c;}cout<<endl;p=g.tellg();cout<<"p="<<p<<endl;}
ligne1: abcligne2: defp=0ligne1p=6
#include <iostream>using namespace std;int int main(){
cout << "Hello world!" << endl;return 0;
}
#include<iostream>using namespace std;#include <limits.h>int main(){cout<<"sizeof(int)="<<sizeof(int)<<endl;cout<<"CHAR_BIT="<<CHAR_BIT<<endl;}
sizeof(int)=4CHAR_BIT=8
00010001 00000000 00000000 00000000
Classe | char | short int | int | long | float | double |
Taille (en byte) | 1 | 2 | 4 | 4 | 4 | 8 |
#include<iostream>using namespace std;#include <bitset>int main(){int i=17;cout<<"La variable int i="<<i<<" est de taille "<<sizeof(i)<<" bytes."<<endl;unsigned char *p=(unsigned char*)&i; // Le pointeur p est l’adresse memoire de icout<<"Contenu des bytes, en ecriture base 10:"<<endl;for(int i=0; i<sizeof(i);i++)cout<<" "<<(int)p[i];cout<<endl<<"Contenu des bytes, en ecriture base 2:"<<endl;for(int i=0; i<sizeof(i);i++)cout<<" "<<bitset<8>(p[i]);cout<<endl;}
La variable int i=17 est de taille 4 bytes.Contenu des bytes, en ecriture base 10:17 0 0 0Contenu des bytes, en ecriture base 2:00010001 00000000 00000000 00000000
cout <<(int)’A’ << endl; // --affiche 65 qui est le code ASCII de Acout <<(char)(65) << endl; //--affiche A qui a pour code ASCII: 65
#include <stdlib>#include <iostream>using namespace std;#include <fstream>#include <iomanip>int main(){double x=3.14;int i=17;int nx=sizeof(double); //nombre de byte occupés par un objet de classe doubleint ni=sizeof(int); //nombre de byte occupés par un objet de classe intcout<<"nx= "<<nx<<" ni= "<<ni<<endl;//===============================ofstream sortie( "donnees.dat ",ofstream::binary); //ouverture d un fichier en ecriture --sortie.write(&x, nx); //--- ecriture de x ---sortie.write(&i, ni); //--- ecriture de i ---sortie.close(); //- fermeture du fichier --//===============================ifstream entree( "donnees.dat ", ifstream::binary); //-- ouverture d un fichier en lecture --entree.read(&x, nx); //--- lecture de x ---entree.read(&i, ni); //--- lecture de i ---cout<<" x= "<<x<<" i= "<<i<<endl;entree.seekg(nx); // on se positionne après nx octets en partant du début, soit après la valeur de xentree.read(&i, ni); //--- lecture de i ---cout<<" i= "<<i<<endl;int pos=entree.tellg(); // donne la position du curseur dans le fichier (en byte)cout<<"la position du curseur est maintenant: "<<pos<<endl;}
#include <iostream> // pour coutusing namespace std;#include <stdlib.h> // pour system//----Fonction principale ----------------int main(){system("ls"); // execute la commande ls. (affiche les fichiers)}
#ifdef TOTO//... do something#elif//.. do something#endif
#include <iostream> using namespace std; extern"C" { void fortfunc_(int *ii, float *ff); } main() { int ii=5; float ff=5.5; fortfunc_(&ii, &ff); return 0; }
subroutine fortfunc(ii,ff) integer ii real*4 ff write(6,100) ii, ff 100 format(’ii=’,i2,’ ff=’,f6.3) return end
// -*- mode:C++ ; compile-command: "gfortran -c mod_zbes.f90; gfortran -c testF.f; g++ -c testC.cc; g++ -o test mod_zbes.o testF.o testC.o -lgfortran" -*- // execute command: ./test #include <iostream> using namespace std; #include <boost/math/special_functions/bessel.hpp> // for cyl_bessel typedef struct{double r; double i;} COMPLEX2; //--------------------------------- extern"C" { //... use small capital for the function name void bessel_(COMPLEX2 *znu, COMPLEX2 *zz, COMPLEX2 *zans, int *info); } //--------------------------------- int main(int argc, char **argv) { //... input COMPLEX2 znu, zz; znu.r = 1; // real part znu.i = 0; // imag part zz.r = 1; zz.i = 0; cout<<"order nu = ("<<znu.r<<","<<znu.i<<")"<<", argument z = ("<<zz.r<<","<<zz.i<<")"<<endl; //... output int info; COMPLEX2 zans; bessel_(&znu, &zz, &zans, &info); cout<<"Result: J_nu(z) = ("<<zans.r<<","<<zans.i<<")"<<endl; cout<<"info = "<<info<<", (0 is OK)"<<endl; cout<<"Compare with boost library: J_nu.r(z.r) = "<<boost::math::cyl_bessel_j(znu.r, zz.r)<<endl; return 0; }
subroutine bessel(znu,zz,zans,info) USE mod_zbes,ONLY: kp,bessel1,bessel2,hankel1,hankel2 COMPLEX (kp), INTENT (IN) :: znu, zz COMPLEX (kp), INTENT (OUT) :: zans INTEGER, INTENT (OUT) :: info CALL bessel1(znu, zz, zans, info) return end
double operator*(Vect v2){
double p=0;p=x*v2.x+y*v2.y+z*v2.z;return p;}
int main(){
double d;Vect v(1,2,3);Vect w(2,3,4);d=v*w;cout <<”d=” << d << endl;}
Vect operator-(){
return (*this)*(-1);}
int main(){
Vect v(1,2,3);Vect w;w=-v;w.Affiche();}
friend Vect operator*(double a,Vect v2){
return (v2*a);}
int main(){
double d(2);Vect v(1,2,3);Vect w;w=d*v;}
friend ostream & operator <<(ostream & sortie, Vect v2){
sortie "Vecteur: " v2.x "|" v2.y "|" v2.z "|";return sortie;}
int main(){
Vect v(1,2,3);cout v endl;}
//---- variables membres
int N; //tailledouble *element; //pointeur
Vect (const Vect & v2){
// ... code à écrire (exercice)...}
v=w;
Vect & operator=(const Vect & v2){
// ... code à écrire (exercice)...}
//== fichier main.cc ============= #include <iostream> using namespace std; #include "main.h" int main() { Vect v; v.x=1; cout<<"Norme de v="<<v.Norme()<<endl; cout<<"3*3="<<f(3)<<endl; }
//== fichier autres.cc ============= #include "main.h" #include <math.h> //--- contenu du constructeur Vect::Vect() { x=0; y=0; z=0; } //-----contenu de la fonction Norme double Vect::Norme() { return sqrt(x*x+y*y+z*z); } //--- code de la fonction f double f(double x) { return x*x; }
//== fichier main.h ============= #if !defined(__MAIN_H) #define __MAIN_H //------ d’une classe class Vect { public: double x,y,z; Vect(); // constructeur double Norme(); }; // ----- declaration d’une fonction double f(double x); #endif
#if !defined(__MAIN_H)#define __MAIN_H...#endif
ne sont pas nécessaires ici mais sont souvent utiles: ce sont des instructions du “préprocesseur” c’est à dire que au moment de la compilation, si le compilateur voit le code intermédiaire ... la première fois, il le considère (et met la variable __MAIN_H à 1). Les fois suivantes, il ne considère par cette partie de code. L’intérêt de cela est que si le fichier main.h se trouve répété à cause d’inclusions multiples (par exemple le fichier A.cc inclut main.h et B.h, et le fichier B.h inclut main.h), alors le code n’est écrit qu’une seule fois, ce qui évite une erreur de “code déjà déclaré”.
g++ -c main.cc -o main.og++ -c autres.cc -o autres.og++ main.o autres.o -o main
# --- fichier Makefile main.o: main.cc main.h g++ -c main.cc -o main.o autres.o: autres.cc main.h g++ -c autres.cc -o autres.o final : main.o autres.o g++ main.o autres.o -o main
# --- fichier Makefile # .... librairies LIBR = -lm # ... instructions de compilation CC =g++ -std=c++11 OBJETS= main.o autres.o main.o: main.cc main.h $(CC) -c $*.cc -o $@ autres.o: autres.cc main.h $(CC) -c $*.cc -o $@ final : main.o autres.o $(CC) $(OBJETS) -o main $(LIBR) lib: ar r main clean: rm *.o
rm -rf .git # si besoin d’effacer ancienne version
git remote add origin https://gricad-gitlab.univ-grenoble-alpes.fr/faurefre/juce_template.gitgit branch -m maingit add .git commit -m "Initial commit"git push -u origin maingit config --global init.defaultBranch main
https://gricad-gitlab.univ-grenoble-alpes.fr/faurefrecompte: faurefregit init # la 1ere foisgit status;git fetch origin main:main # recupere les modifsgit merge maingit remote add origin https://gricad-gitlab.univ-grenoble-alpes.fr/faurefre/juce_template.gitgit branch -M main// ..............................git clone https://gricad-gitlab.univ-grenoble-alpes.fr/faurefre/juce_template.git # telecharge projet et cree repertoire juce_templategit config --global credential.helper "cache --timeout=3600" # permet de stocket mdp pendant 1hgit add . # ajoute tous les repertoires et fichiers
/*! \mainpage Titre\section Nom_sectiontexte...*/
Header 1 {#labelid}========## Header 2 ## {#labelid2}[Link text](#labelid)[Link text](@ref labelid)- Item 1More text for this item.- Item 2+ nested list item.+ another nested item.- Item 31. First item.2. Second item.lignes:- - -______single asterisks*_single underscores_double asterisks**__double underscores__The link text](http://example.net/)[The link text](http://example.net/ "Link title")[The link text](/relative/path/to/index.html "Link title")[The link text](somefile.html)[The link text](@ref MyClass)![Caption text][img def]![img def][img def]: /path/to/img.jpg "Optional Title"http://www.example.com><https://www.example.com><ftp://www.example.com><mailto:address@example.com><address@example.com>First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell| Right | Center | Left || ----: | :----: | :---- || 10 | 10 | 10 || 1000 | 1000 | 1000 |This is a paragraph introducing:~~~~~~~~~~~~~~~~~~~~~a one-line code block~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.c}int func(int a,int b) { return a*b; }~~~~~~~~~~~~~~~```also a fenced code block```Mathematical Inline Formula:\f$\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}\f$.or\f[|I_2|=\left| \int_{0}^T \psi(t)\left\{u(a,t)-\int_{\gamma(t)}^a\frac{d\theta}{k(\theta,t)}\int_{a}^\theta c(\xi)u_t(\xi,t)\,d\xi\right\} dt\right|\f]or\f{eqnarray*}{g &=& \frac{Gm_2}{r^2} \\&=& \frac{(6.673 \times 10^{-11}\,\mbox{m}^3\,\mbox{kg}^{-1}\,\mbox{s}^{-2})(5.9736 \times 10^{24}\,\mbox{kg})}{(6371.01\,\mbox{km})^2} \\&=& 9.82066032\,\mbox{m/s}^2\f}
#include <TApplication.h>#include <TCanvas.h>#include <TLine.h>#include <TEllipse.h>#include <TMarker.h>#include <TBox.h>#include <TText.h>int main(){TApplication theApp("App", nullptr, nullptr);//.. La fenetreTCanvas *c=new TCanvas("titre","titre",400,400);c->Range(0,0,1,1);//.. une ligne bleueTLine *l=new TLine(0.1,0.5,0.3,0.9); // x1,y1,x2,y2.l->SetLineColor(kBlue); // bleul->Draw();//.. Une Ellipse (ou cercle)TEllipse *e= new TEllipse(0.2,0.3,0.1); // (centre (x,y) et rayon re->Draw();//.. Un pointTMarker *m=new TMarker(0.3,0.4,8); // (x,y) et 6 ou 8: forme du Markerm->SetMarkerColor(kPink);m->Draw();//.. Un rectangle vertTBox *p=new TBox(0.15,0.6,0.25,0.7); // on precise les coins bas-gauche (x1,y1) et haut droit (x2,y2) :p->SetFillColor(kGreen);p->Draw();//.. Du texteTText *texte=new TText(0.2,0.2,"un petit texte"); // position x,ytexte->Draw();c->Update(); // Montre le dessintheApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TLine.h>int main(){TApplication theApp("App", nullptr, nullptr);//.. La fenetreTCanvas c("titre","titre",10,10,400,400); //position x,y sur l’ecran et taille X,Y en pixelsc.Range(0,0,10,10); // xmin,ymin,xmax,ymax, systeme de coordonnees//.. une ligne bleueTLine l;l.SetLineColor(kBlue); // bleul.DrawLineNDC(0,0,1,1); // coordonnées universelles (0,1,0,1)//.. une ligne rougeTLine l2;l2.SetLineColor(kRed); // rougel2.DrawLine(5,0,5,10); // coordonnées definies par Range()c.Update(); // Montre le dessintheApp.Run(); // garde la fenetre ouverte et permet a l’utilisateur d’interagir.}
#include <TApplication.h>#include <TCanvas.h>#include <TMarker.h>int main(){TApplication theApp("App", nullptr, nullptr);TCanvas c1("c1","fenetre1",400,400); // creation de la fenetre c1TCanvas c2( "c2","fenetre2",400,400); // creation de la fenetre c2TMarker *m1=new TMarker(0.3,0.4,8); // un pointTMarker *m2=new TMarker(0.3,0.4,8); // un pointm2->SetMarkerColor(kRed);c1.cd(); // choix de la fenetre c1 pour le prochain dessinm1->Draw(); // dessin du point 1c2.cd(); // choix de la fenetre c2 pour le prochain dessinm2->Draw(); // dessin du point 2theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>int main(){TApplication theApp("App", nullptr, nullptr);TCanvas *c=new TCanvas("titre","titre",400,400);double x1(0),y1(0),x2(2),y2(1); // position du cadrec->DrawFrame(x1,y1,x2,y2);theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TEllipse.h>#include <TH1F.h>int main(){TApplication theApp("App", nullptr, nullptr);TCanvas *c=new TCanvas("titre","titre",400,400);double x1(0),y1(0),x2(10),y2(10); // position du cadreTH1F *h =c->DrawFrame(x1,y1,x2,y2);TEllipse e(2,3,1);e.Draw();h->SetXTitle("x");h->SetYTitle("y");h->SetMinimum(-2); // change les bornes en yh->SetMaximum(8);h->SetBins(1000,1,5); // change les bornes en x: 1->5c->Update(); // Montre le dessintheApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TGaxis.h>int main(){TApplication theApp("App", nullptr, nullptr);TCanvas *c=new TCanvas("titre","titre",400,400);double x1(0.1),y1(0.5),x2(0.9),y2(0.5); // position de l’axedouble v1(0),v2(1); // graduations extremesTGaxis axe(x1,y1,x2,y2,v1,v2,510,"");axe.SetTitle("x"); // met le titre sur l’axeaxe.Draw();theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TStyle.h>#include <TColor.h>#include <TH3.h>//====================main (){TApplication theApp("App", nullptr, nullptr);//---- on defini une palette de 5 couleursconst int n = 5; //nbre de couleursfloat rgb[n * 3] ={0.9f, 0.60f, 0.f,0.f, 1.f, 1.f,1.f, 0.f, 0.f,0.f, 1.f, 0.f,1.f, 1.f, 0.f};int palette[n] = {0};for (Int_t i = 0; i < n; ++i)palette[i] = TColor::GetColor(rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2]);gStyle->SetPalette(n, palette);//------------------------gStyle->SetCanvasPreferGL(kTRUE); // permet d’utiliser openGLTCanvas *c = new TCanvas("glc","TH3 Drawing", 400,400);int N=50;double x1=-3,x2=3,y1=-3,y2=3,z1=-3,z2=3;TH3D *h = new TH3D("h", "h", N, x1, x2, N, y1, y2, N, z1, z2);for(int i=0;i<N;i++)for(int j=0;j<N;j++)for(int k=0;k<N;k++){double x= (x2-x1)*i*1./N+x1;double y= (y2-y1)*j*1./N+y1;double z= (z2-z1)*k*1./N+z1;double f= exp(-x*x-y*y-z*z); // formule f(x,y,z)h->SetBinContent(i+1,j+1,k+1, f);}h->SetFillColor(kBlue);h->SetContour(n);h->Draw("gliso");// glbox1 glbox glcol glisotheApp.Run();}
#include <TApplication.h>#include <TF1.h>int main(){TApplication theApp("App", nullptr, nullptr);//------------TF1 *f1 = new TF1("f1","sin(x)/x",0,10);f1->Draw();//-------------------theApp.Run();}
#include <TApplication.h>#include <TF1.h>//---------------------double F(double *px, double *p){double x= px[0];return sin(x)/x;}//---------------int main(){TApplication theApp("App", nullptr, nullptr);//------------TF1 *f1 = new TF1("f1",F,0,10);f1->Draw();//-------------------theApp.Run();}
#include <TApplication.h> #include <TF1.h> #include <TH1.h> //--defines a function------------------- double F(double *px, double *p) { double x= px[0]; if(x>1) return 0; else return (1. - pow(x, 3/2.)); } //--------------- int main() { TApplication theApp("App", nullptr, nullptr); //------------ TF1 *f1 = new TF1("1-(T/T_{B})^{3/2}",F,0,2); f1->Draw(); //... draw axis lables TH1 * h = f1->GetHistogram(); h->SetXTitle("T/T_{B}"); h->SetYTitle("N_{0} / N"); //------------------- theApp.Run(); }
#include <TApplication.h>#include <TH1.h>int main(){TApplication theApp("App", nullptr, nullptr);//------------int nx(10); // nombre de pointsdouble xmin(0.0),xmax(1.0); // graduation de l’axe xTH1D *h1=new TH1D("nom","titre",nx,xmin,xmax);h1->SetXTitle("x");h1->SetYTitle("y");for(int i=1;i<=nx;i++) // remplissage{double z=i*i;h1->SetBinContent(i,z);}h1->SetStats(0);// pas de boite de resultats stath1->SetMarkerStyle(8);//8: gros pointh1->Draw("L P"); // option L: ligne ou P: marker//-------------------theApp.Run();}
#include <TApplication.h>#include <TPie.h>int main(){TApplication theApp("App", nullptr, nullptr);//------------int n= 5; // nbre de valeursdouble valeurs[5] = {.2, 1.1, .6, .9, 2.3};int couleurs[5] = {2,3,4,5,6};TPie *p = new TPie("p", "titre", n, valeurs, couleurs);p->Draw();//-------------------theApp.Run();}
#include <TApplication.h>#include <TGraph.h>#include <TPad.h>#include <TAxis.h>int main(){TApplication theApp("App", nullptr, nullptr);//---- creation de tableauxint n = 100;double x[100], y[100];for (int i=0;i<n;i++) // remplissage{double r = i;x[i] = r*cos(0.3* i);y[i] = r*sin(0.3 * i);}//--- dessinTGraph *gr = new TGraph(n,x,y);gr->SetLineColor(kBlue);gr->SetMarkerColor(kRed);gr->SetMarkerStyle(6); // 6:petit cercle 8: grosgr->GetXaxis()->SetTitle("X");gr->GetYaxis()->SetTitle("Y");gr->Draw("A C P"); // AC: trace un segment entre les points// gPad->BuildLegend(); // rajoute la legende//-------------------theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TGraphPolar.h>int main(){TApplication theApp("App", nullptr, nullptr);TCanvas * c = new TCanvas("CPol","TGraphPolar Example",500,500);int N=50;double theta[N];double radius[N];for (int i=0; i<N; i++){theta[i] = i*(2*M_PI/N);radius[i] = sin(theta[i])* sin(theta[i]) +1 ;}TGraphPolar * grP1 = new TGraphPolar(N, theta, radius);grP1->SetFillColor(kRed);grP1->Draw("f");c->Update();theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TGraphPolar.h>int main(){TApplication theApp("App", nullptr, nullptr);TCanvas * c = new TCanvas("CPol","TGraphPolar Example",500,500);double theta[8];double radius[8];double etheta[8];double eradius[8];for (int i=0; i<8; i++) {theta[i] = (i+1)*(M_PI/4.);radius[i] = (i+1)*0.05;etheta[i] = M_PI/8.;eradius[i] = 0.05;}TGraphPolar * grP1 = new TGraphPolar(8, theta, radius, etheta, eradius);grP1->SetTitle("TGraphPolar Example");grP1->SetMarkerStyle(20);grP1->SetMarkerSize(2.);grP1->SetMarkerColor(kBlue);grP1->SetLineColor(kRed);grP1->SetLineWidth(3);grP1->Draw("PE");c->Update();theApp.Run();}
#include <TRandom.h>#include <TApplication.h>#include <TCanvas.h>#include <TF1.h>#include <TH1.h>#include <iostream>using namespace std;int main(){TApplication theApp("App", nullptr, nullptr);TCanvas *c=new TCanvas("titre","titre",400,400);//------- cree histo avec tirage aleatoire avec loi gaussienne ------------int nbin=100; double xmin=-3,xmax=3;TH1D *h=new TH1D("TW","TW",nbin,xmin,xmax);gRandom->SetSeed(); // initialise sur l’horlogefor(int i=1;i<=1e5;i++) //tirages{double x= gRandom->Gaus(0,1); // c’est P(x)=exp(-0.5*(x/sigma)^2)h->Fill(x);}h->Draw();//---- calcule integrale et normalise l’histogramme -----------double I= h->Integral();h->Scale(1/I);h->Draw();//--- Fit l’histogramme avec une Gaussienne --------------TF1 *f1 = new TF1("f1","gaus"); // ou pol0, pol1,...polN pour polynome degre N, ou expoh->Fit("f1");cout<<"Ecart type ="<<f1->GetParameter(2)<<endl;//--- montre fenetres de commandes ---h->DrawPanel();h->FitPanel();//------c->Update();//------theApp.Run();}
#include <TApplication.h>#include <TH1.h>#include <THStack.h>int main(){TApplication theApp("App", nullptr, nullptr);//---- cree un histogramme --------int nx(10); // nombre de pointsdouble xmin(0.0),xmax(1.0); // graduation de l’axe xTH1D *h1=new TH1D("nom","titre",nx,xmin,xmax);h1->SetXTitle("x");h1->SetYTitle("y");for(int i=1;i<=nx;i++) // remplissage{double z=i*i;h1->SetBinContent(i,z);}h1->SetFillColor(kGreen);//-------------- une copie ----------TH1D *h2 = (TH1D*)h1->Clone();h2->SetFillColor(kRed);//-------------------------THStack *hs = new THStack("hs","");hs->Add(h1);hs->Add(h2);hs->Draw(); // dessin les uns sur les autres. nostack: superposes , nostackb, lego1//-------------------theApp.Run();}
#include <TApplication.h>#include <TH2D.h>int main(){TApplication theApp("App", nullptr, nullptr);//------------int nx(10),ny(10);double xmin(0),xmax(1),ymin(0),ymax(2);TH2D *h= new TH2D("h1","titre",nx,xmin,xmax,ny,ymin,ymax);h->SetXTitle("x");h->SetYTitle("y");h->SetStats(kFALSE); // pas de panneau statfor(int i=1;i<=nx;i++) // remplissagefor(int j=1;j<=ny;j++){double z=i*j;h->SetCellContent(i,j,z);}h->Draw("surf2"); // essayer options: surf1, surf3,surf4,lego//-------------------theApp.Run();}
#include <TApplication.h>#include <TF2.h>#include <TStyle.h>int main(){TApplication theApp("App", nullptr, nullptr);//------------gStyle->SetCanvasPreferGL(kTRUE); //si option gl.. cidessousTF2 *f2 = new TF2("f2","-sin(x)*sin(y)/(x*y)",0,5,0,5);f2->Draw("surf4"); // glsurf1, glsurf2, glsurf3, glsurf3, glsurf1cyl, glsurf1pol, glsurf1sph//-------------------theApp.Run();}
#include <TApplication.h>#include <TGraph2D.h>#include <TCanvas.h>#include <TRandom.h>#include <TStyle.h>using namespace std;main (){TApplication theApp("App", nullptr, nullptr);TCanvas *c = new TCanvas("c","Graph2D example",0,0,600,400);double x, y, z, P = 6.;int N = 200;TGraph2D *g = new TGraph2D();TRandom *r = new TRandom();for(int i=0; i<N; i++){x = 2*P*(r->Rndm(N))-P; // choix de (x,y) au hasard dans le carré [-P,P]y = 2*P*(r->Rndm(N))-P;z = (sin(x)/x)*(sin(y)/y)+0.2; // formule de la surface lisseg->SetPoint(i,x,y,z); // ajoute point (x,y,z) a l’ensemble}gStyle->SetPalette(1); // couleurs. autres choix: 0, 1, 2g->Draw("tri1"); // autres choix: tri, triw, tri1, tri2, p,po, pcol,linetheApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TArrow.h>#include <TLine.h>#include <math.h>#include <iostream>using namespace std;///--- definition du champ de vecteurvoid vect(double x, double y, double &vx, double &vy){vx = x ;vy= -y;}//----------------------------------int main(){TApplication theApp("App", nullptr, nullptr);//------------double xmin=-1, xmax=1, ymin=-1,ymax=1; // coordonnéesTCanvas *c=new TCanvas("c","c",500,500); // fenetrec->DrawFrame(xmin,ymin,xmax,ymax);//------------------double N=20; // nbre d’echantillonsdouble dx=(xmax-xmin)/N;double dy=(ymax-ymin)/N;for (int i=0; i<N; i++)for (int j=0; j<N; j++){double x=xmin + dx*i;double y=ymin + dy*j;double vx,vy;vect(x,y,vx,vy);// calcul les coordonnées du champ de vecteurvx *= dx *1; // normalisevy *= dy *1;double n=sqrt(vx*vx+vy*vy); // normeTArrow *t= new TArrow(x,y,x+vx,y+vy,dx*n);// TLine *t= new TLine(x,y,x+vx,y+vy);t->Draw();} // for i,j//—-donne la main a l’utilisateur (A)—theApp.Run();}
#include <TApplication.h>#include <TPolyMarker3D.h>int main(){TApplication theApp("App", nullptr, nullptr);//------------int N=1000;//nbre de pointsTPolyMarker3D *p = new TPolyMarker3D(N);for( int i = 0; i < N; i++ ){double theta=i/double(N)*2*M_PI;double x=cos(theta), y=sin(theta), z=cos(10*theta);p->SetPoint( i, x, y, z );}p->SetMarkerSize( 1 );p->SetMarkerColor( kBlue);p->SetMarkerStyle( 8 );p->Draw();//-------------------theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TStyle.h>#include <TFormula.h>#include <TF3.h>//-----------------------------main (){TApplication theApp("App", nullptr, nullptr);gStyle->SetCanvasPreferGL(true);auto c = new TCanvas("c", "TF3: Surface", 0, 0, 600, 600);TF3 *tf3 = new TF3("Surface, option gl=0","x*y*z+0.2", -1,1,-1,1,-1,1);tf3->Draw("glfbbb");//------------------------theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TStyle.h>#include <TFormula.h>#include <TF3.h>//-----------------------------main (){TApplication theApp("App", nullptr, nullptr);auto c = new TCanvas("c", "TF3: Surface", 0, 0, 600, 600);TF3 *tf3 = new TF3("Surface option gl=0","x*y*z", -1,1,-1,1,-1,1);tf3->Draw("FBBB");//------------------------theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TStyle.h>#include <TFormula.h>#include <TF3.h>//-----------------------------main (){TApplication theApp("App", nullptr, nullptr);gStyle->SetCanvasPreferGL(true);auto c = new TCanvas("c", "TF3: Surface", 0, 0, 600, 600);TFormula f1 = TFormula("f1", "x*x + y*y + z*z + 2*y - 1");TFormula f2 = TFormula("f2", "x*x + y*y + z*z - 2*y - 1");TF3 *tf3 = new TF3("Klein Bottle","f1*(f2*f2-8*z*z) + 16*x*z*f2",-3.5, 3.5, -3.5, 3.5, -2.5, 2.5);tf3->SetFillColor(kRed);tf3->Draw("glFB");//------------------------theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TStyle.h>#include <TH3.h>main (){TApplication theApp("App", nullptr, nullptr);gStyle->SetCanvasPreferGL(kTRUE); // mettre avant declaration de la fenetre TCanvasTCanvas *c = new TCanvas("glc","TH3 Drawing", 400,400);int N=30;double x1=-3,x2=3,y1=-3,y2=3,z1=-3,z2=3;TH3D *h = new TH3D("h", "h", N, x1, x2, N, y1, y2, N, z1, z2);for(int i=0;i<N;i++)for(int j=0;j<N;j++)for(int k=0;k<N;k++){double x= (x2-x1)*i*1./N+x1;double y= (y2-y1)*j*1./N+y1;double z= (z2-z1)*k*1./N+z1;double f= exp(-x*x-y*y-z*z); // formule f(x,y,z)h->SetBinContent(i+1,j+1,k+1, f);}h->SetFillColor(kBlue);double levels[2] = {2, 2.5}; // valeurs des niveauxh->SetContour(2,levels); // on choisit deux niveaux pour le dessin isoh->Draw("gliso");// glbox1 glbox glcol glisotheApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TStyle.h>#include <TH3.h>main (){TApplication theApp("App", nullptr, nullptr);//-------------------double C0=2; // niveau souhaiteTCanvas *c = new TCanvas("glc","TH3 Drawing", 400,400);int N=30;double x1=-3,x2=3,y1=-3,y2=3,z1=-3,z2=3;TH3D *h = new TH3D("h", "h", N, x1, x2, N, y1, y2, N, z1, z2);double sum=0;for(int i=0;i<N;i++)for(int j=0;j<N;j++)for(int k=0;k<N;k++){double x= (x2-x1)*i*1./N+x1;double y= (y2-y1)*j*1./N+y1;double z= (z2-z1)*k*1./N+z1;double f= sqrt(x*x+y*y+z*z); // fonctionh->SetBinContent(i+1,j+1,k+1, f);sum+=f;}double delta = -sum + (N*N*N) *C0;h->SetBinContent(1,1,1, h->GetBinContent(1,1,1)+delta);h->SetFillColor(kBlue);h->Draw("iso");theApp.Run();}
#include <TApplication.h>#include <TCanvas.h>#include <TStyle.h>#include <TH3.h>#include <TPolyMarker3D.h>main (){TApplication theApp("App", nullptr, nullptr);//-------------------double C0=2; // niveau souhaiteTCanvas *c = new TCanvas("glc","TH3 Drawing", 400,400);int N=30;double x1=-3,x2=3,y1=-3,y2=3,z1=-3,z2=3;TH3D *h = new TH3D("h", "h", N, x1, x2, N, y1, y2, N, z1, z2);double sum=0;for(int i=0;i<N;i++)for(int j=0;j<N;j++)for(int k=0;k<N;k++){double x= (x2-x1)*i*1./N+x1;double y= (y2-y1)*j*1./N+y1;double z= (z2-z1)*k*1./N+z1;double f= sqrt(x*x+y*y+z*z); // fonctionh->SetBinContent(i+1,j+1,k+1, f);sum+=f;}double delta = -sum + (N*N*N) *C0;h->SetBinContent(1,1,1, h->GetBinContent(1,1,1)+delta);h->SetFillColor(kBlue);h->Draw("iso");//------------int N2=1000;//nbre de pointsTPolyMarker3D *p = new TPolyMarker3D(N2);for( int i = 0; i < N2; i++ ){double theta=i/double(N2)*2*M_PI;double x=2*cos(theta), y=2*sin(theta), z=0;p->SetPoint( i, x, y, z );}p->SetMarkerSize( 1 );p->SetMarkerColor( kRed);p->SetMarkerStyle( 8 );p->Draw();//-------------------theApp.Run();}
#include <TApplication.h> #include <TCanvas.h> #include <TGeoManager.h> #include <TEveManager.h> #include <TGLViewer.h> //----------------------------- int main() { TApplication theApp("App", nullptr, nullptr); double R=1, R2=0.2; // radius double L = 0.5; //length TGeoManager * geom = new TGeoManager("sphere", "spheres"); //--- define the global domain TGeoMaterial *mat = new TGeoMaterial("Al"); TGeoMedium *med = new TGeoMedium("MED",1,mat); double X= 10*R, Y=10*R, Z=10*R; TGeoVolume *top = geom->MakeBox("TOP",med, X,Y,Z); // This is the global domain. (can be MakeTube also) geom->SetTopVolume(top); TGeoMaterial *mat2 = new TGeoMaterial("ball"); TGeoMedium *ball = new TGeoMedium("ball", 1, mat2); //------------ object 1: spheres TGeoVolume *o1 = geom->MakeSphere("SPHERE", ball, 0., R); // name, medium, rmin, rmax, thetamin=0, thetamax=180, phimin=0, phimax=360 o1->SetLineColor(kRed); for(int i=0; i<4; i++) { //... center double x = 0; double y = 0; double z = i * 3 * R; top->AddNode(o1, i, new TGeoTranslation(x, y, z)); } //------------ object 2: cylinders TGeoVolume *o2 = geom->MakeTube("tube", ball, 0., R2, L); // name, medium, rmin, rmax, dz = half lenght o2->SetLineColor(kBlue); for(int i=0; i<4; i++) { double x =0; double y = 0; double z = 1.5+ i * 3 * R; top->AddNode(o2, i, new TGeoTranslation(x, y, z)); } //------------------ geom->CloseGeometry(); top->Draw("ogl"); // "ogl" - OpenGL viewer, "x3d" auto gv = (TGLViewer*) gPad->GetViewer3D() ; gv->SetClearColor(kBlack); // fond noir gv->UpdateScene(); // Update //------------------------ theApp.Run(); }
#include <iostream>using namespace std;#include <TCanvas.h>#include <TMarker.h>#include <TApplication.h>#include <TEllipse.h>//====Ma Classe Fenetre================================class Fenetre: public TCanvas{public:// constructeur ......Fenetre(Text_t* name, Text_t* title, Int_t ww, Int_t wh) : TCanvas(name,title,ww,wh){ }//—- Cette fonction est appelle si la souris s’agitte. ——void HandleInput(EEventType event, Int_t px, Int_t py){//– affiche l’etat de la souris ——–cout<<" position: px="<<px<<" py="<<py<<" code du bouton="<<event<<endl;//– convertit la position en pixel px,py en coordonnees (x,y) ——double x = gPad->AbsPixeltoX(px);double y = gPad->AbsPixeltoY(py);// si bouton gauche appuye dessine un point —if(event==1){TMarker *m=new TMarker(x,y,8);m->Draw();Update();}//—————— Event clavier ——————–if (event==kKeyPress) // touche appuyée{cout<<"touche px="<<px<<endl;switch (px){//——— change de mode (tempéré <-> juste) ——–case ’m’:cout<<"Touche m appuyée"<<endl;break;}; // switch px} // if event}};///--------------------------------------------int main(){TApplication theApp("App", nullptr, nullptr);Fenetre *c = new Fenetre("c", "fenetre1", 400,400); // crée une fenetredouble xmin(0),ymin(0),xmax(5),ymax(5);c->Range(xmin,ymin,xmax,ymax); // coordonnees de la fenetre (optionnel, par defaut: 0-1)theApp.Run();}
#include <iostream>using namespace std;#include <TCanvas.h>#include <TApplication.h>#include <TEllipse.h>//==============class Cercle: public TEllipse{public:// constructeur ......Cercle(double x, double y, double r): TEllipse(x,y,r){ }int col = kRed;//—- Cette fonction est appelle si la souris s’agitte. ——void ExecuteEvent(int event, int px, int py){//--- change l’epaisseur du cercleSetLineWidth(3);Draw();gPad->Update();SetLineWidth(1);Draw();//--- si clique gaucheif(event == 1){if(col == kRed)col = kBlue;elsecol = kRed;SetFillColor(col);Draw();}}};///--------------------------------------------int main(){TApplication theApp("App", nullptr, nullptr);TCanvas *c = new TCanvas("c", "fenetre1", 400,400); // crée une fenetredouble xmin(0),ymin(0),xmax(4),ymax(4);c->Range(xmin, ymin, xmax, ymax); // coordonnees de la fenetre (optionnel, par defaut: 0-1)Cercle *C1= new Cercle(3,2,0.5);C1->SetFillColor(kRed);C1->Draw();Cercle *C2= new Cercle(1,2,0.5);C2->SetFillColor(kRed);C2->Draw();theApp.Run();}
gSystem->ProcessEvents(); // avec #include <TSystem>
#include <TApplication.h>#include <TCanvas.h>#include <TEllipse.h>#include "bib_fred.cc"///------------------------------------int main(){TApplication theApp("App", nullptr, nullptr);TCanvas *c= new TCanvas("c","fenetre",400,400);double xmin(-1),ymin(-1),xmax(2),ymax(2);c->Range(xmin,ymin,xmax,ymax);int periode = 10; // temps entre chaque image en 1/100e sec.int imin=1, imax=30;for(int i =imin; i<=imax ; i++){double x = i/(double)imax;TEllipse e(x,0.5,1);e.Draw(); // dessine l’ellipsec->Update();Animation(c,i,imin,imax,"film",periode); // -> crée fichier film.gif}theApp.Run();}
/*! =========================== * Exemple simple d'une fenetre de commande. * Il y a deux classes: la classe Com qui est la fenetre de commande * et qui permet de commander une autre classe A * Chaque classe a un lien vers l'autre afin de pouvoir communiquer. */ #include <TCanvas.h> #include <TGFrame.h> #include <TGButton.h> #include <TGComboBox.h> #include <TGTextEntry.h> #include <TGLabel.h> #include <TGProgressBar.h> #include <TPad.h> #include <TFrame.h> #include <TH1F.h> #include<TSystem.h> #include <TGNumberEntry.h> #include <TGSlider.h> #include <TGDoubleSlider.h> #include <TGTripleSlider.h> #include <TGMenu.h> #include <TApplication.h> #include <TRootEmbeddedCanvas.h> #include <thread> #include <chrono> #include <iostream> using namespace std; class A; // classe definie après /*!==========fenetre de commandes ======================== * Description de la classe Com */ class Com: public TGMainFrame // (derivee d une fenetre GUI) { public : TGMenuBar *fMB; // barre de menu TGPopupMenu *fM; // menu TGTextButton *fB; // bouton TGTextEntry *fT; // zone texte TGLabel *fL; // texte fixe ecrit sur la fenetre TGComboBox *fC; // liste deroulante TGCheckButton *fCB; TGHProgressBar *fH; // barre de progres TGNumberEntry *fNE; TGHSlider *fS; TGDoubleVSlider *fS2; TGTripleHSlider *fS3; TRootEmbeddedCanvas *fEC; // fenetre //------------------- A *a; // lien vers un objet a d'une classe A //--------------------- Com(A *a_i); // constructeur ~Com(); // destructeur Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t); // fonction appelee si action sur les commandes //========================================= // met a jour les valeurs de la fenetre void Met_a_jour(); // fonction qui met à jour les valeurs de la fenetre à partir des parametres de l'objet a }; /*!=============== * Une classe pour effectuer un calcul ... */ class A { public: double x; //------------- void Calcul() { cout<<"calcul:"; for(x=1; x<=50; x++) { this_thread::sleep_for(chrono::milliseconds {100}); // attend 0.5 ms// attente, com->Met_a_jour(); cout<<x<<","<<flush; } cout<<endl; } //------------ Com *com; // pointeur vers l'objet fenetre de control void Lance_commandes() { TApplication theApp("App", NULL,NULL); com= new Com(this); // cree fenetre de control et l'associe a l'objet present theApp.Run(); //----donne la main a l'utilisateur --- } }; /*!===================== Constructeur */ Com::Com(A *a_i) : TGMainFrame(gClient->GetRoot(),400,350) // taille de la fenetre { a=a_i; // initialise le lien vers l'objet à controller (sera utile pour les commandes) a->com=this; //---------------- SetWindowName("Fenetre de commandes"); // nom de la fenetre //--------- Menu ---------- fMB = new TGMenuBar(this, 35, 50, kHorizontalFrame); AddFrame(fMB, new TGLayoutHints(kLHintsTop | kLHintsExpandX, 2, 2, 2, 5)); fM=fMB->AddPopup("&Menu"); fM->AddEntry("&Option 1",3); fM->AddSeparator(); fM->AddEntry("O&ption 2",4); fM->Associate(this); //-----boutons ------------------------ fB= new TGTextButton(this,"S&tart",2); // cree bouton, lettre t, et code message 2 fB->Move(100,10); // position x,y fB->SetToolTipText("Demarre un calcul ..."); // texte d'aide fB->Associate(this); fB->Resize(80, fB->GetDefaultHeight()); // taille (x,y) //..Label = texte fixe................. fL= new TGLabel(this, new TGString("Label = Texte fixe")); fL->Move(10,40); // position x,y //...Zone de texte ................ string text="toto"; fT = new TGTextEntry(this,text.c_str(),1); //code 1 fT->Move(10,70); // position x,y fT->Resize(40,fT->GetDefaultHeight()); // taille (x,y) char buf[100]="texte"; fT->Associate(this); //------- Liste Combo ---- fC = new TGComboBox(this, 88); fC->AddEntry("entree 1",1); fC->AddEntry("entree 2",2); fC->Resize(150, 20);// taille (x,y) fC->Select(2); // selection a priori AddFrame(fC, new TGLayoutHints(kLHintsTop | kLHintsLeft,5,5,5,5)); // mise en association fC->Move(10,100); // position //----- Progress Bars-------------- fH = new TGHProgressBar(this,TGProgressBar::kFancy,300); fH->ShowPosition(); fH->SetBarColor("green"); fH->Move(10,130); // position fH->SetRange(0.0,50.); // min, max fH->SetPosition(10.); // position fH->ShowPosition(kTRUE,kFALSE,"valeur: %.0f"); //----------- Sliders ----------- fS = new TGHSlider(this,150,kSlider1|kScaleDownRight,2); // simple, Id=2 fS->SetRange(0,50); fS->SetPosition(39); fS->Move(10,200); fS2 = new TGDoubleVSlider(this,100,kDoubleScaleNo,3); //double fS2->SetRange(-10,10); fS2->Move(200,200); fS3 = new TGTripleHSlider(this,100,kDoubleScaleBoth,4, //triple kHorizontalFrame); fS3->SetConstrained(kTRUE); fS3->SetRange(0,10); fS3->SetPosition(2,3); fS3 ->SetPointerPosition(2.5); fS3->Move(250,200); //-------- entree numerique ------ double val=3.1415; fNE = new TGNumberEntry(this, val, 5, 400,(TGNumberFormat::EStyle) 2); // 5: longueur du nombre, 400: Id fNE->Associate(this); fNE->Move(10,250); // position //----- Fenetre Canvas -------------- fEC = new TRootEmbeddedCanvas("ec1", this, 200, 100); AddFrame(fEC, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 5, 5, 5, 5)); // les options disent comme la fenetre se comporte si on maximise ou change la taille fEC->Move(200,10); TCanvas *c = fEC->GetCanvas(); c->DrawFrame(0,0,1,1); c->Update(); // c->Modified(); //....Check Button fCB= new TGCheckButton(this,":bouton check",420); fCB->SetToolTipText("texte d'aide pour bouton check"); fCB->Associate(this); fCB->Resize(120, fCB->GetDefaultHeight()); fCB->Move(10,280); //------------ MapSubwindows(); // dessin des objets (bouttons ,...) MapWindow(); // dessin de la fenetre } /*!==================================== * Destructeur */ Com::~Com() { delete fB; delete fT; delete fH; delete fC; } /*!==================================== * Fonction appelee lorsque l'utilisateur agit sur la fenetre de commandes * -> Ici on gère les actions */ Bool_t Com::ProcessMessage(Long_t msg, Long_t p1, Long_t p2) { int M = GET_MSG(msg), S=GET_SUBMSG(msg); cout<<" M = "<<M<<" S = "<<S<<" p1="<<p1<<" p2="<<p2<<endl; switch (M) { case 1: switch (S) { case 3: switch(p1) { case 2: cout<<"bouton 2"<<endl; a->Calcul(); break; } break; case 4: if(p1==420) { cout<<"bouton check .. "<<endl; if(fCB->IsOn()) cout<<" on."<<endl; else cout<<" off."<<endl; } break; case 7: cout<<"combo choisi: "<<fC->GetSelected()<<endl; break; } case 4: switch (S) { case 1: cout<<"texte change"<<endl; switch (p1) { case 1: cout<<"Le nouveau texte est: "<<((fT->GetBuffer())->GetString())<<endl; break; case 400: cout<<"Le nouveau chiffre est: "<<((fNE->GetNumber()))<<endl; break; } break; } break; default: break; } Met_a_jour(); return kTRUE; } /*! ========================================= * Fonction appelée par une fonction externe * pour mettre a jour les valeurs de la fenetre, */ void Com::Met_a_jour() { fH->SetPosition(a->x); // progress Bar // gClient->NeedRedraw(fH); gSystem->ProcessEvents(); // handle GUI events } /*!===Main================================================ */ int main(int argc, char **argv) { A *a=new A; a->Lance_commandes(); return 0; }
/*! =========================== * Exemple simple d'une fenetre de commande. * avec Menu et Tab et sous fenetre libre */ #include <TCanvas.h> #include <TGFrame.h> #include <TGButton.h> #include <TGMenu.h> #include <TApplication.h> #include <TGTab.h> #include <iostream> using namespace std; //---- identifieurs (int) pour les messages de commandes enum Command_id { M_1, M_2, M_3, M_4, B_1, B_2 }; //==================================== // Fenetre secondaire class Fen2 : public TGTransientFrame { public: //---- constructeur Fen2(const TGWindow *p, const TGWindow *main, UInt_t w, UInt_t h, UInt_t options = kVerticalFrame): TGTransientFrame(p, main, w, h, options) { SetCleanup(kDeepCleanup); //--------- zone avec bouton auto fFrame1 = new TGHorizontalFrame(this, 60, 20, kFixedWidth); auto fOkButton = new TGTextButton(fFrame1, "&Ok", B_1); fOkButton->Associate(this); fFrame1->AddFrame(fOkButton); AddFrame(fFrame1); //--------- MapSubwindows(); Resize(); // resize to default size CenterOnParent(); // position relative to the parent's window SetWindowName("2eme fenetre"); MapWindow(); //fClient->WaitFor(this); // otherwise canvas contextmenu does not work } //---- destructeur virtual ~Fen2() { // Delete test dialog widgets. } //------ virtual void CloseWindow() { cout<<"fenetre Fen2 fermee��?"<<endl; // Add protection against double-clicks // fOkButton->SetState(kButtonDisabled); DeleteWindow(); } //------ virtual Bool_t ProcessMessage(Long_t msg, Long_t p1, Long_t p2) { int M = GET_MSG(msg), S=GET_SUBMSG(msg); cout<<" Fen2: M = "<<M<<" S = "<<S<<" p1="<<p1<<" p2="<<p2<<endl; } }; /*!==========fenetre principales ======================== */ class Com: public TGMainFrame { public : int X=300, Y=150; // taille en pixels //===== Constructeur Com() : TGMainFrame(gClient->GetRoot(), X,Y) { SetCleanup(kDeepCleanup); //?? //-- regles de positionnement TGLayoutHints *fLH_TX = new TGLayoutHints(kLHintsTop | kLHintsExpandX , 2, 2, 2, 5); TGLayoutHints *fLH_C = new TGLayoutHints(kLHintsCenterX | kLHintsExpandX | kLHintsExpandY,5,5,5,5); TGLayoutHints *fLH_L = new TGLayoutHints(kLHintsLeft,5,5,5,5); TGLayoutHints *fLH_R = new TGLayoutHints(kLHintsRight,5,5,5,5); //--------- Menu ---------- TGMenuBar *fMB = new TGMenuBar(this, X, Y);//, kHorizontalFrame); AddFrame(fMB, fLH_TX); TGPopupMenu *fM=fMB->AddPopup("&Menu1"); fM->AddEntry("&Fenetre",M_1); fM->AddSeparator(); fM->AddEntry("O&ption 2",M_2); fM->Associate(this); TGPopupMenu *fM2=fMB->AddPopup("&Menu2"); fM2->AddEntry("&Option 1",M_3); fM2->AddSeparator(); fM2->AddEntry("O&ption 2",M_4); fM2->Associate(this); //--------- zone superieure auto * fFrame1 = new TGHorizontalFrame(this, X, Y);//, kFixedWidth); AddFrame(fFrame1, fLH_L); //.. bouton 1 TGButton *fOkButton = new TGTextButton(fFrame1, "&Ok ", B_1); fOkButton->Associate(this); fFrame1->AddFrame(fOkButton, fLH_L); //.. bouton 2 TGButton *fOkButton2 = new TGTextButton(fFrame1, "&Ok2", B_1); fOkButton2->Associate(this); fOkButton2->Move(50,50); fFrame1->AddFrame(fOkButton2, fLH_L); //----- Tab ------------------ TGTab *fTab = new TGTab(this, X,Y); AddFrame(fTab); //.. Tab1 ----------- TGCompositeFrame *tf1 = fTab->AddTab("Tab 1"); //.. bouton 1 TGTextButton * fB1 = new TGTextButton(tf1, "&Bouton 1 LLLLLL", B_2); fB1->Associate(this); tf1->AddFrame(fB1); //.. bouton 2 TGTextButton * fB2 = new TGTextButton(tf1, "&Bouton 2", B_2); fB2->Associate(this); tf1->AddFrame(fB2); //.. Tab2 .................. TGCompositeFrame *tf2 = fTab->AddTab("Tab 2"); //-- fenetre generale----------- MapSubwindows(); Resize(); MapWindow(); SetWindowName("Fenetre de commandes"); // nom de la fenetre } //=========================== ~Com() // destructeur { } //===================================== Bool_t ProcessMessage(Long_t msg, Long_t p1, Long_t p2) { int M = GET_MSG(msg), S=GET_SUBMSG(msg); cout<<"Fen: M = "<<M<<" S = "<<S<<" p1="<<p1<<" p2="<<p2<<endl; if(M==1 && S==1 && p1 ==M_1 && p2== 0) new Fen2(fClient->GetRoot(), this, 400, 200); // nouvelle fenetre return kTRUE; } }; // fin de la classe /*!===Main================================================ */ int main(int argc, char **argv) { TApplication theApp("App", nullptr, nullptr); Com *com= new Com(); // cree fenetre de control et l'associe a l'objet present theApp.Run(); //----donne la main a l'utilisateur --- return 0; }
#include <TGFrame.h> #include <TGTab.h> #include <TRootEmbeddedCanvas.h> #include <TCanvas.h> #include <TH1F.h> #include <TApplication.h> //=========================== void fsarazin() { const char *moni_histoname[] = {"moni_1", "moni_2","moni_3","moni_4","moni_5",0}; const char *offline_histoname[] = {"off_1","off_2","off_3","off_4","off_5",0}; TGLayoutHints *hint = new TGLayoutHints(kLHintsExpandX|kLHintsExpandY,2,2,2,2); TGLayoutHints *hint_plots = hint; // main frame TGMainFrame *mainFrame = new TGMainFrame(gClient->GetRoot(),500, 300); TGTab *tab = new TGTab(mainFrame, 1, 1); TGCompositeFrame *moniFrame = tab->AddTab("Monitoring data"); TGTab *monitab = new TGTab(moniFrame,1,1); moniFrame->AddFrame(monitab,hint_plots); TGCompositeFrame *moni_hTab[5]; TRootEmbeddedCanvas *moni_Canvas[5]; for (int i=0;i<5;i++) { moni_hTab[i] = monitab->AddTab(moni_histoname[i]); moni_Canvas[i] = new TRootEmbeddedCanvas(moni_histoname[i], moni_hTab[i], 500, 300); moni_hTab[i]->AddFrame(moni_Canvas[i], hint); } TGCompositeFrame *offlineFrame = tab->AddTab("Offline data"); TGTab *offlinetab = new TGTab(offlineFrame,1,1); offlineFrame->AddFrame(offlinetab,hint_plots); TGCompositeFrame *offline_hTab[5]; TRootEmbeddedCanvas *offline_Canvas[5]; for (int i=0;i<5;i++) { offline_hTab[i] = offlinetab->AddTab(offline_histoname[i]); offline_Canvas[i] = new TRootEmbeddedCanvas(offline_histoname[i], offline_hTab[i], 500, 300); offline_hTab[i]->AddFrame(offline_Canvas[i], hint); } tab->Resize(tab->GetDefaultSize()); mainFrame->AddFrame(tab, hint); TH1F *m_h[5]; for (int i=0;i<5;i++) { m_h[i] = new TH1F(moni_histoname[i], moni_histoname[i], 100, -5, 5); m_h[i]->FillRandom("gaus",15000); m_h[i]->SetFillColor(i+2); m_h[i]->SetFillStyle(3004); moni_Canvas[i]->GetCanvas()->cd(); m_h[i]->Draw(); moni_Canvas[i]->GetCanvas()->Update(); } TH1F *o_h[5]; for (int i=0;i<5;i++) { o_h[i] = new TH1F(offline_histoname[i], offline_histoname[i], 100, 0, 50); o_h[i]->FillRandom("landau",15000); o_h[i]->SetFillColor(i+2); o_h[i]->SetFillStyle(3004); offline_Canvas[i]->GetCanvas()->cd(); o_h[i]->Draw(); offline_Canvas[i]->GetCanvas()->Update(); } mainFrame->MapSubwindows(); mainFrame->Resize(mainFrame->GetDefaultSize()); mainFrame->MapWindow(); mainFrame->Resize(900,600); } //=========================== int main() { TApplication theApp("App", nullptr, nullptr); fsarazin(); theApp.Run(); //----donne la main a l'utilisateur --- }
#include <TQObject.h>#include <RQ_OBJECT.h>class A {RQ_OBJECT("A")private:Int_t fValue;public:A() : fValue(0) { }~A() { }void SetValue(Int_t value); // *SIGNAL*void PrintValue() const { printf("value = %d\n", fValue); }};void A::SetValue(Int_t value) { // Set new value// Emit signal "SetValue(Int_t)" with a single parameterif (value != fValue) {fValue = value;Emit("SetValue(Int_t)", fValue);}}// Main program#ifdef STANDALONEint main(int argc, char **argv) {A* a = new A();A* b = new A();a->Connect("SetValue(Int_t)", "A", b, "SetValue(Int_t)");printf("n******* Test of SetValue(Int_t) signal *******n");b->SetValue(10);printf("nt***** b before ******n");b->PrintValue();a->SetValue(20);printf("t***** b after a->SetValue(20) ******n");b->PrintValue();return 0;}#endif
#include <TRandom.h>gRandom->SetSeed(0); // initialise le hasard sur l’horlogedouble x= gRandom->Uniform(2); // nombre aléatoire dans l’intervalle (0,2)
TCanvas *canvas = 0;canvas = (TCanvas *)gROOT->GetListOfCanvases()->FindObject("canvas2");
canvas->SetWindowPosition(Int_t x, Int_t y); // move the container window in a different position into the screencanvas->SetWindowSize(UInt_t ww, UInt_t wh); //resize the container window (not the contained canvas)canvas->RaiseWindow(); // to move the canvas window in front of all windows on the desktop.
#include <TROOT.h>
#include <chrono>using namespace std::chrono;#include <iostream>using namespace std;int main(){auto t1=high_resolution_clock::now(); // mesure du "time point 1"//....... instruction qui prend du temps .....for(int i=0;i<1e5;i++)cout<<" \t"<<i<<flush;//.............auto t2=high_resolution_clock::now(); // mesure du "time point 2"auto dt1=duration_cast<nanoseconds>(t2-t1).count(); // calcul de la durée en nsauto dt2=duration_cast<milliseconds>(t2-t1).count(); // calcul de la durée en msauto dt3=duration_cast<duration<double>>(t2-t1).count(); // calcul de la durée en scout<<"durée: "<<dt1<< "ns"<<" = "<<dt2<< "ms"<<" = "<<dt3<<" s."<<endl;}
auto tt=system_clock::to_time_t(t1); // convertit au type time_tcout << "Maintenant c’est: " << ctime(&tt);
#include <thread>#include <chrono>using namespace std::chrono;using namespace std::this_thread;sleep_for(seconds{2}); // attend 2 secondessleep_for(milliseconds{3}); // attend 3 millisecondes
#include <iostream>#include <thread>#include <chrono>using namespace std::chrono;using namespace std::this_thread;using namespace std;main (){auto t1 = high_resolution_clock::now(); // date actuellecout<<" J’attends 3 secondes"<<endl;auto t2 = t1 + seconds {3}; // date futuresleep_until(t2); // attenteauto t3 = high_resolution_clock::now(); // date mesuréeauto dt = duration_cast<duration<double>>(t3-t1).count(); // mesure dt = t3-t1cout<<"La durée a été dt = "<<dt<<" s."<<endl;}
#include <iostream> #include <boost/array.hpp> #include <boost/numeric/odeint.hpp> #include <TApplication.h> #include <TCanvas.h> #include <TMarker.h> #include <TH1F.h> using namespace std; using namespace boost::numeric::odeint; const double sigma = 10.0; const double R = 28.0; const double b = 8.0 / 3.0; const int N=3; //nbre de variables de l’EDO ///—- definition de la fonction à intégrer————————– void lorenz( const array<double,N> &x , array<double,N> &dxdt , double t ) { dxdt[0] = sigma * ( x[1] - x[0] ); dxdt[1] = R * x[0] - x[1] - x[0] * x[2]; dxdt[2] = -b * x[2] + x[0] * x[1]; } ///—————————— int main() { TApplication theApp("App", nullptr, nullptr); TCanvas *c = new TCanvas( "c","fenetre",500,500); // on precise la taille en pixels double xmin(-30),ymin(0),xmax(30),ymax(50); TH1F *h=c->DrawFrame(xmin,ymin,xmax,ymax); // coordonnees de la fenetre (optionnel, par defaut: 0-1) h->SetXTitle("x1"); h->SetYTitle("x2"); int cpt=0; array<double,N> x = { 10.0 , 1.0 , 1.0 }; // conditions initiales double t1 =0 ,t2=100; // temps initial et final double dt =0.002; //pas de temps for(double t=t1; t<=t2; t=t+dt) { integrate( lorenz , x , t, t+dt, dt); // integre entre t et t+dt // cout << t << ’\t’ << x[0] << ’\t’ << x[1] << ’\t’ << x[2] << endl; cpt++; TMarker *p=new TMarker(x[1],x[2],6); p->Draw(); TMarker p2(x[1],x[2],8); p2.SetMarkerColor(kRed); p2.SetMarkerSize(2); p2.Draw(); if(cpt%10==0) c->Update(); } c->Update(); theApp.Run(); }
#include <iostream>using namespace std;#include <TCanvas.h>#include <TMarker.h>#include <TApplication.h>#include "bib_fred.cc"///--------------------------------------------int main(){TApplication theApp("App", nullptr, nullptr);//---- lecture audio du fichier wav avec le logiciel vlcsystem("vlc Voyelles_Par_Malik.wav");//--- lecture de tout le fichiervec signal;double f=Lecture_fichier_wav("Voyelles_Par_Malik.wav", signal); // transfert les données du fichier dans le vecteurdouble dt=1./f; // pas en temps//Dessin(signal, "signal");Dessin(signal,"s","s",0,signal.size()*dt,"signal",0,"L",-1e4,1e4,kBlue,0);//--- lecture d’une partievec signal2;double t1=4, t2=4.03; // intervalle de temps en secondesf=Lecture_fichier_wav("Voyelles_Par_Malik.wav", signal2, 1,t1,t2);dt=1./f;//Dessin(signal2, "s2");Dessin(signal2,"s","s",t1,t1+signal2.size()*dt,"signal2",0,"L",-1e4,1e4,kRed,0);//---------theApp.Run();}
#include <iostream>using namespace std;#include <TCanvas.h>#include <TMarker.h>#include <TApplication.h>#include "bib_fred.cc"///--------------------------------------------int main(){TApplication theApp("App", nullptr, nullptr);double dt=1./48000; // pas de temps en s.double T=5;// durée en s.int N=T/dt;vec signal(N);double f0=440; // frequence de la note que l’on veut en Hzfor(int i=0; i<N; i++){double t=i*dt;double f= f0 *(1+0.01*cos(2.*M_PI*t/1.)); // modulation de frequencesdouble s= sin( 2*M_PI * f * t ); // note pure de frequence fs = s + 0.5 * sin( 2*M_PI * 2*f * t ); // rajoute harmonique 2s = s + 0.3 * sin( 2*M_PI * 3*f * t ); // rajoute harmonique 3signal(i) = s;}Dessin(signal,"s","s",0,signal.size()*dt,"signal",0,"L",-4,4,kBlue,0);// ecrit le vecteur signal dans le fichier son.wav. On indique dtEcriture_fichier_wav(signal, dt,"son.wav");//---- lecture audio du fichier wav avec le logiciel vlcsystem("vlc son.wav");//---------theApp.Run();}
=====Crée un fichier wav à partir du tableau ====fichier:son.wavNombre de canaux=1Frequence d’echantillonage=48000 HzBits par echantillon=16Nombre d’octets par echantillon=2Nombre d’ echantillons =240000Pas de temps dt =2.08333e-05 s.Durée T =5 s.
// -*- mode:C++ ; compile-command: "g++ -Wall -D__LINUX_ALSA__ -o sinus sinus.cc ../RtAudio.cpp -lasound -lpthread" -*- //---------------- #include "../RtAudio.h" #include <iostream> using namespace std; #include <math.h> #include <unistd.h> #define SLEEP( milliseconds ) usleep( (unsigned long) (milliseconds * 1000.0) ) unsigned int nchan = 2; // 1: mono, 2: stereo int mode = 1; // 0: rec, 1: play 2:rec&play //============================= /* input: N inbuf[i], i=0->N-1 t0 : time of inbuf[0] output: outbuf[i], i=0->N-1 */ static int audio_event(void *outbuf, void *inbuf, unsigned int N, double t0, RtAudioStreamStatus status, void *userdata) { double *buf1 = (double*)inbuf; double *buf2 = (double*)outbuf; //---------------------- if(mode == 0) //record { if(nchan == 1) // mono for(int i=0; i< (int)N; i= i+1) cout<<buf1[i]<<","; else // stereo for(int i=0; i< 2*(int)N; i= i+2) cout<<"("<<buf1[i]<<","<<buf1[i+1]<<"),"; } //---------------------- if(mode == 1) //play { if(nchan == 1) // mono for(int i=0; i< (int)N; i= i+1) { double t = t0 + i/(44100.); buf2[i] = 0.1* sin( 2 * M_PI * 440 * t ); } else // stereo for(int i=0; i< 2*(int)N; i= i+1) { double t = t0 + i/(2*44100.); if(i%2==0) buf2[i] = 0.1* sin( 2 * M_PI * 440 * 3./4.* t ); // quarte else buf2[i] = 0.1* sin( 2 * M_PI * 440 * t ); } } //---------------------- if(mode == 2) //rec & play { if(nchan == 1) // mono for(int i=0; i< (int)N; i= i+1) buf2[i] = 0.1* buf1[i]; else // stereo for(int i=0; i< 2*(int)N; i= i+1) buf2[i] = 0.1* buf1[i]; } return 0; // means ok } //========================================== int main(void) { RtAudio *audio; unsigned int bufsize = 256; // size of buffers, = 2^k. void * data = nullptr; audio = new RtAudio(); RtAudio::StreamParameters *inParam = nullptr; if(mode ==0 || mode ==2) { inParam =new RtAudio::StreamParameters(); inParam->deviceId = audio->getDefaultInputDevice(); inParam->nChannels = nchan; } RtAudio::StreamParameters *outParam = nullptr; if(mode == 1 || mode ==2) { outParam = new RtAudio::StreamParameters(); outParam->deviceId = audio->getDefaultOutputDevice(); outParam->nChannels = nchan; } audio->openStream(outParam, inParam, RTAUDIO_FLOAT64, 44100, &bufsize, audio_event, (void*) data); audio->startStream(); sleep(20); audio->stopStream(); audio->closeStream(); delete audio; return 0; }
g++ -Wall -D__LINUX_ALSA__ -o sinus sinus.cc ../RtAudio.cpp -lasound -lpthread
g++ -Wall -D__LINUX_PULSE__ -o sinus sinus.cc ../RtAudio.cpp -lpulse-simple -lpulse -lpthread
./sinus
0 [HDMI ]: HDA-Intel - HDA Intel HDMIHDA Intel HDMI at 0xf7a1c000 irq 381 [PCH ]: HDA-Intel - HDA Intel PCHHDA Intel PCH at 0xf7a18000 irq 37
#include "bib_fred.cc"#include "audio.cc"#include <iostream>using namespace std;#include <TROOT.h>#include <TApplication.h>//===Main================================================int main(){TApplication theApp("App", nullptr, nullptr);Audio s;s.Initialise_audio(1); // initialise la carte son en entree (1) et affiche ses informationsint N=1000; // on donne la taille que l’on veut (nombre d’echantillons)vec V(N);while(1) // boucle infinie{s.Lit_donnees_audio(V); // remplit V depuis le microDessin(V,"V");// Dessin(V,"t","s",0,N*s.Dt,"V",0,"L",-1e4,1e4,kRed,0); // dessin normalisé en rouge}/// ----Donne la main a l’utilisateur ---theApp.Run();}
Periode : T=0.0034036s. <-> Frequence f=1/T=293.806 HzNote =Re, Ecart = 0.00833494 demitons, Octave=0.
#include "bib_fred.cc" #include "audio.cc" #include <iostream> using namespace std; #include <TROOT.h> #include <TApplication.h> string Notes[12] = {"Do","Do#", "Re","Re#", "Mi", "Fa", "Fa#", "Sol", "Sol#", "La", "La#", "Si"}; //===Main================================================ int main() { TApplication theApp("App", nullptr, nullptr); Audio s; s.Initialise_audio(1); // initialise la carte son en entree (1) et affiche ses informations int N=2000; // on donne la taille que l’on veut (determine la fenetre temporelle) vec V(N); //parametres pour la detection de la periode int NP=2; // 1,2: nbre de periodes à afficher double f_A = 440; // diapason s.seuil_norme_par_I=1e4; s.seuil_C =0.1; s.verbose =0; //1 affiche messages erreur //--------------------- while(1) // boucle infinie { s.Lit_donnees_audio(V); // remplit V depuis le micro double t0 =0; // date de debut d’analyse int opt_dessin_C=0; // 0 ou 1 double T=s.Detecte_Periode(V, t0, opt_dessin_C); // -> Periode T ou 0 if(T>0) { double f=1/T; cout<<" Periode : T="<<T<<"s. <-> Frequence f=1/T="<<f<<" Hz"<<endl; //--- conversion en note de musique double nu = 12*log(f/f_A)/log(2.) + 69; int nu_i = floor(nu+0.5); cout<<" Note ="<<Notes[nu_i%12]<<" Ecart = "<<nu-nu_i<<" demitons"<<" Octave="<<nu_i/12-5<<endl; //---- affiche NP periodes extraites vec Extrait = V.rows( t0/s.Dt, (t0+NP*T)/s.Dt); // on extrait NP periodes uword i = Extrait.index_max(); Extrait =shift(Extrait, -i ); // place le max de l’extraitau debut Dessin(Extrait,"t","s",0,NP*T,"Extrait",0,"L",-1111,-1111,kRed,0); // dessin normalisé } } /// ----Donne la main a l’utilisateur --- theApp.Run(); }
#include "bib_fred.cc" #include "audio.cc" #include <iostream> using namespace std; #include <TROOT.h> #include <TApplication.h> int main() { TApplication theApp("App", nullptr, nullptr); Audio s; s.Initialise_audio(3); // initialise la carte son en entree et sortie (3) et affiche ses informations vec V; while(1) // boucle infinie { s.Lit_donnees_audio(V); // micro -> V Dessin(V,"t","s",0,V.size()*s.Dt,"V",0,"L",-1e4,1e4,kRed,0); // dessin de V s.Ecrit_donnees_audio(V); // V -> Haut Parleur } /// ----Donne la main a l’utilisateur --- theApp.Run(); }
Il peut être utile dans un projet de répartir le travail entre plusieurs programmes qui fonctionnent ensemble et communiquent. Un ordinateur est capable de gérer plusieurs programmes qui fonctionnent. Si l’ordinateur ne possède qu’un processeur, il va faire avancer chaque programme tour à tour en alternant sur des intervalles de temps très court. Cela donne l’impression que plusieurs programmes fonctionnent en parallèle. On va s’interesser à la communication entre ces programmes.On peut imaginer cela comme des travailleurs qui fabriquent une maison. Chacun travaille sur sa partie mais il y a des moments où ils doivent échanger des informations, parfois un travailleur doit attendre qu’un autre ait fini son travail. Alors c’est le chef de projet (le processeur) qui se charge de superviser tout cela, de mettre en attente certains et réactiver d’autres.Il y a donc trois concepts importants dont nous allons voir la mise en oeuvre:
#include <iostream> // std::coutusing namespace std;#include <thread>//---- Une petite fonction qui affiche des “a”----------------void f(int n){for(int i=0;i<n;i++)cout<<"a"<<flush;cout<<endl;}//----Fonction principale ----------------int main(){ // ici la fonction main est lancéeint n=10;thread t(f,n); // lance la fonction f(n) dans un threadcout << "Les fonctions main et f sont maintenant en concurrence.\n";for(int i=0;i<n;i++) // affiche des “b”cout<<"b"<<flush;cout<<endl;t.join(); // attend ici que la fonction f soit finiecout << "f est finie.\n";}
Les fonctions main et f sont maintenant en concurrence.bbbbbaaaaaaaaaabbbbbf est finie.
#include <iostream>using namespace std;#include <thread>class A{public:void f(int n ) { cout << "n=" << n << endl; }};int main(){A a;thread t1(&A::f, &a, 100);t1.join();}
n=100
#include <iostream> // std::coutusing namespace std;#include <thread>//---- Une petite fonction qui affiche n fois n ----------------void f(int n){for(int i=0; i<n; i++)cout<<n<<flush;}//----Fonction principale ----------------int main(){int n=7;thread L_t[n]; // tableau de threadsfor (int i=0; i<n; i++)L_t[i] = thread(f,i); // lance de thread i qui affiche i fois ifor(int i=0; i<n; i++)L_t[i].join(); // attend ici que le thread i soit fini}
#include <iostream> // std::cout #include <atomic> // std::atomic, std::memory_order_relaxed #include <thread> // std::thread using namespace std; atomic<int> X(0); //---------------------------- void set(int x) { X.store(x, memory_order_relaxed); // set value atomically } //------------------------ void print() { int x; do { x = X.load( memory_order_relaxed); // get value atomically cout << "x=" << x <<endl; } while (x==0); cout << "X=" << x <<endl; } //------------------ int main () { thread first(print); thread second(set, 10); first.join(); second.join(); return 0; }
x=0x=10X=10
mutex mtx;
#include <iostream> // std::coutusing namespace std;#include <thread>#include <mutex>mutex mtx;//--------------------void f(int n,char c){mtx.lock(); // si mtx est libre on le bloque, sinon on attendfor(int i=0;i<n;i++)cout<<c<<flush;cout<<endl;mtx.unlock(); // débloque mtx}//--------------------int main(){int n=10;thread t1(f,n,’a’);thread t2(f,n,’b’);t1.join();t2.join();}
aaaaaaaaaabbbbbbbbbb
scoped_lock lck {mutex1,mutex2,mutex3};
shared_mutex mx;
unique_lock lck {mx};
condition_variable cv;
cv.wait(lck);
cv.notify_one();
#include <iostream>using namespace std;#include <thread>#include <chrono>#include <mutex>#include <condition_variable>mutex mtx;condition_variable cv;//--------------------void f(){unique_lock<mutex> lck(mtx); // bloque le mutex mtx. Il sera debloque automatiquement par wait(lck), ou a la destruction de lck.cv.wait(lck); // met le thread en attente (endormi). Il sera réveillé par un signal extérieur.cout<<"FIN"<<endl;}//--------------------int main(){thread t(f);cout<<"On attend 2sec."<<endl;this_thread::sleep_for(chrono::seconds{2});cout<<"voilà."<<endl;// ... reveille cvcv.notify_one(); // reveille le thread endormi//.........t.join();}
On attend 2sec.voilà.FIN
#include <iostream>using namespace std;#include <thread>#include <chrono>#include <mutex>#include <condition_variable>mutex mtx;condition_variable cv;//——————–void f1(){while(1){this_thread::sleep_for(chrono::milliseconds {1000});cout<<"1"<<flush;cv.notify_one(); // reveille le thread main() endormi}}//——————–void f2(){while(1){this_thread::sleep_for(chrono::milliseconds {1502});cout<<"2"<<flush;cv.notify_one(); // reveille les thread main() endormi}}//——————–int main(){thread t1(f1);thread t2(f2);unique_lock<mutex> lck(mtx); // bloque le mutex mtx. Il sera debloque automatiquement par wait(lck), ou a la destruction de lck.while(1){cv.wait(lck); // met le thread main() en sommeilcout<<","<<flush;}//.........t1.join();t2.join();}
#include <iostream>using namespace std;#include <thread>#include <chrono>#include <mutex>#include <condition_variable>mutex mtx;condition_variable cv;//——————–void f1(){unique_lock<mutex> lck(mtx); // bloque le mutex mtx. Il sera debloque automatiquement par wait(lck), ou a la destruction de lck.cout<<"a"<<endl;cv.wait(lck);cout<<"b"<<endl;}//——————–void f2(){unique_lock<mutex> lck(mtx); // bloque le mutex mtx. Il sera debloque automatiquement par wait(lck), ou a la destruction de lck.cout<<"A"<<endl;cv.wait(lck);cout<<"B"<<endl;}//——————–int main(){thread t1(f1);thread t2(f2);for(int t=3; t>=0; t--) // compte à rebour{this_thread::sleep_for(chrono::seconds {1});cout<<t<<","<<flush; // \r permet de re-ecrire au debut de la ligne}cout<<"partez!"<<endl;cv.notify_all();//.........t1.join();t2.join();}
aA3,2,1,0,partez!bB
#include <iostream> using namespace std; #include <thread> #include <chrono> #include <mutex> #include <condition_variable> #include <list> mutex mtx; condition_variable cv; list<int> L; int N=10; //-------------------- void f() { while(1) // boucle infinie { { unique_lock<mutex> lck(mtx); // bloque le mutex mtx. Il sera debloque par wait(lck) ou a la destruction de lck if(L.size()< N) // si liste non pleine cv.wait(lck); // debloque le mutex lck et met le thread en attente (endormi), de facon atomique. Il sera réveillé par un signal extérieur venant de cv.notify_one(); } // ici lck est detruit donc mtx est debloque mtx.lock(); cout<<"Liste pleine. On vide la liste par le debut:"<<flush; while(L.size()>0) { cout<<L.front()<<","<<flush; this_thread::sleep_for(chrono::milliseconds {100}); L.pop_front(); // enleve le premier element } cout<<endl; mtx.unlock(); cv.notify_one(); // reveille le thread endormi } } //-------------------- int main() { thread t(f); // lance la fonction f dans un thread while(1) // boucle infinie { mtx.lock(); // bloque le mutex if(L.size()==0) // si liste vide { cout<<"Liste Vide. Remplit la liste:"<<flush; for(int j=0; j< N; j++) { cout<<j<<","<<flush; L.push_back(j); this_thread::sleep_for(chrono::milliseconds {100}); } cout<<endl; } mtx.unlock(); // debloque cv.notify_one(); // reveille le thread endormi // se met en attente unique_lock<mutex> lck(mtx); cv.wait(lck); } //......... t.join(); return 0; }
#include <iostream>using namespace std;#include <chrono>using namespace std::chrono;#include <future>//-----------------------double calculus(double x, double y){this_thread::sleep_for(chrono::seconds {2});return x*y;}//--------------------------int main(){auto t1=high_resolution_clock::now(); // mesure du "time point 1"auto a1 = async(calculus,3,3); // thread 1auto a2 = async(calculus,4,4); // thread 2auto a3 = async(calculus,5,5); // thread 3auto t2=high_resolution_clock::now(); // mesure du "time point 2"auto dt = duration_cast<duration<double>>(t2-t1).count(); // calcul de la durée en mscout<<"3*3+4*4-5*5="<< a1.get() + a2.get()- a3.get()<<", calcul en "<<dt<<" ms"<<endl;}
3*3+4*4-5*5=0, calcul en 2.24e-06 ms
<!DOCTYPE html> <html> <head> </head> <body> <form method="post" action="http://localhost:8080/cgi-bin/cgi_test1_local.cgi"> Your name : <input type="text" name="nom" /><br /> Your age : <input type="text" name="age" /><br /> <input name="envoi" type="submit"> </form> </body> </html>
// -*- mode:C++ ; compile-command: "/home/faure/c++/essais/cgi_/exemple_1/script_de_demarrage_test1_local" -*- /* 1er Test de cgi de (cgicc) (exemple plus complet: voir animations_web.cc" Compilation -------------------- sur serveur labo: script_de_demarrage_test1_labo en local (pas encore au point, revoir le script): script_de_demarrage_test1_local Infos -------------- au labo --------- le programme cgi peut lire/ecrire des fichiers, dans le repertoire local /faure/ qui est accessible depuis l'exterieur par https://www-fourier.ujf-grenoble.fr/~fauretmp/ En local: --------------- Pour un serveur local (maison) , les fichiers peuvent etre mis dans cgi-file/temp/ rem: il faut avoir mit le repertoire en permission ecriture for all */ #include <iostream> using namespace std; #include <cgicc/Cgicc.h> // pour recup�rer l'info des entr�es #include <cgicc/HTTPHTMLHeader.h> // pour r�cup�rer infos sur les variables d'environnement #include <cgicc/HTMLClasses.h>// using namespace cgicc; #include <string> //----------------------- int main(int argc, char **argv) { try { Cgicc cgi; //---- entete du document HTML de sortie ---------------- cout << HTTPHTMLHeader() << endl; cout << html() << head(title("Cgicc example 1")) << endl; cout << body() << endl; //---- On recupere les donnees des widgets //...... version simple sans test string nom = cgi("nom"); // l'element "nom" est defini dans le fichier html qui a declench� ce programme string age = cgi("age"); cout << "Votre nom est: " << nom <<" age = "<<age<<"<br>"<< endl; // idem //...... version avec plus de tests, en particulier si le nom du widget existe ------- form_iterator name = cgi.getElement("nom"); if(! name-> isEmpty() && name != cgi.getElements().end()) { cout << "Je repete, votre nom est: " << name->getValue() <<" <br>"<< endl; // idem } else cout<<"Erreur..<br>"<<endl; //-------------- cout<<endl<<"Script cgi, le 01/12/2020 par c++/essai/cgi_/exemple_1/cgi_test1.cc utilisant la biblioth�que Cgicc"<<endl; cout << body() << html(); //Close the HTML document //----- write in a file on the serveur string nom_fichier = "/faure/essai.txt"; // si serveur labo // string nom_fichier = "../cgi-file/temp/essai.txt"; // si serveur local, ne marche pas? ofstream f; f.open(nom_fichier.c_str(), ios_base::out); // app: rajoute � la suite, out: commence � z�ro f << "Nom = " << nom << endl; f.close(); } //------------------ catch(exception& e) { cout<<"Un probleme..."<<endl; // handle any errors - omitted for brevity } }
#nom de ce fichier: script_de_demarrage_test1_local #compilation: g++ cgi_test1.cc -o cgi_test1 -lm -lcgicc #copie l'executable dans le rep cgi-bin: cp /home/faure/c++/essais/cgi_/exemple_1/cgi_test1 ~/public_html/cgi-bin/cgi_test1_local.cgi #copie le fichier interface html dans le repertoire cgi-file: cp ~/c++/essais/cgi_/exemple_1/cgi_test1_local.html ~/public_html/cgi-file/ #lance un serveur web dans un autre terminal console, meme repertoire que ce projet: cd ~/public_html/ xterm -e python -m CGIHTTPServer 8080 & # ouvre fichier html firefox http://localhost:8080/cgi-file/cgi_test1_local.html
<!DOCTYPE html> <html> <head> </head> <body> <form method="post" action="https://www-fourier.ujf-grenoble.fr/~faure/cgi-bin/cgi_test1_labo.cgi"> Your name : <input type="text" name="nom" /><br /> Your age : <input type="text" name="age" /><br /> <input name="envoi" type="submit"> </form> </body> </html>
#nom de ce fichier: script_de_demarrage_test1_labo #------compilation. Rem l'option -static permet d'embarquer les librairires comme lib statiques et donc que le code soit executable sur le serveur du labo. g++ cgi_test1.cc -o cgi_test1 -lm -lcgicc -static #copie l'executable dans le rep cgi-bin: cp /home/faure/c++/essais/cgi_/exemple_1/cgi_test1 ~/public_html/cgi-bin/cgi_test1_labo.cgi #copie le fichier interface html dans le repertoire cgi-file: cp ~/c++/essais/cgi_/exemple_1/cgi_test1_labo.html ~/public_html/cgi-file/ #--------------copie le repertoire public_html sur le serveur du labo ------------------------- rsync -aLvp --delete -e ssh -P --exclude "error.log" --exclude 'cgi_requests' /home/faure/public_html/ malherbe.ujf-grenoble.fr:/home/faure/public_html #lance le navigateur pour utiliser le programme firefox https://www-fourier.ujf-grenoble.fr/~faure/cgi-file/cgi_test1_labo.html
<form method="post" action="https://www-fourier.ujf-grenoble.fr/~faure/cgi-bin/cgi_test1.cgi?toto">
int main(int argc, char **argv){string chaineif(argc>=2)chaine = argv[1];...
<!DOCTYPE html> <html> <body> <h2>Send data POST by JavaScript</h2> <button type="button" onclick="f()">Action</button> <p id="demo"></p> <script> //---- this function is called by the button 'Action' function f() { var xhttp = new XMLHttpRequest(); //---- send data to the serveur // xhttp.open("POST", "http://localhost:8080/cgi-bin/cgi_test1_local.cgi", true); // local xhttp.open("POST", "https://www-fourier.ujf-grenoble.fr/~faure/cgi-bin/cgi_test1_labo.cgi", true); // labo xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //send a header xhttp.send("nom=Henry&age=12"); // send data forms //---- this function is called after serveur's answer xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) // 4: finished, 200: OK { document.getElementById("demo").innerHTML = this.responseText; // responseText: recieve a string } }; } // f() </script> </body> </html>
cout <<"<META http-equiv=\"Cache-Control\" content=\"no-cache\"> "<<endl; cout <<"<META http-equiv=\"Pragma\" content=\"no-cache\">"<<endl; cout <<"<META http-equiv=\"Expires\" content=\"0\"> "<<endl;
<html> <body> <form enctype="multipart/form-data" method="post" action="https://www-fourier.ujf-grenoble.fr/~faure/cgi-bin/cgi_test1.cgi"> <input type="file" name="the_file"></input> <input type="submit" name="submit" value="send the file"></input> </form> </body> </html>
#include <stdio.h> int main(char ** argv, int argc) { FILE * fp=fopen("/faure/essai.txt", "wb" ); char tmp[1024]; int nRead; while (nRead=fread(tmp, 1, 1024, stdin)) { fwrite(tmp, 1, nRead, fp); } fclose(fp); return 0; }
struct servent {char *s_name; // value = http ,It is the official name of the service. For example, SMTP, FTP POP3, etc.char **s_aliases; // value = ALIAS It holds the list of service aliases. Most of the time, it will be set to NULL.int s_port; // value = 80 It will have the associated port number. For example, for HTTP, it will be 80.char *s_proto; // value = TCP, UDP It is set to the protocol used. Internet services are provided using either TCP or UDP.};
// Server side C/C++ program to demonstrate Socket programming #include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #define PORT 8080 int main(int argc, char const *argv[]) { int server_fd, new_socket, valread; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[1024] = {0}; char *hello = "Hello from server"; // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Forcefully attaching socket to the port 8080 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror("accept"); exit(EXIT_FAILURE); } valread = read( new_socket , buffer, 1024); printf("%s\n",buffer ); send(new_socket , hello , strlen(hello) , 0 ); printf("Hello message sent\n"); return 0; }
// Client side C/C++ program to demonstrate Socket programming #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #define PORT 8080 int main(int argc, char const *argv[]) { int sock = 0, valread; struct sockaddr_in serv_addr; char *hello = "Hello from client"; char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) { printf("\nInvalid address/ Address not supported \n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } send(sock , hello , strlen(hello) , 0 ); printf("Hello message sent\n"); valread = read( sock , buffer, 1024); printf("%s\n",buffer ); return 0; }
port ouvert.Attente de message ..1 messages recus.Message recu sur le port=0: 144, 60, 50Midi::On ferme les ports midi..
port ouvert.J’ai envoye le message 144, 60, 50 sur le port 0Midi::On ferme les ports midi..
//===== Programme test_midi_in.cc ========== #include <iostream> using namespace std; #include "midi.h" int main() { Midi midi; //--- ouvre un port midi en entree int port=0; // numero de port int res = midi.Initialise_port_midi_in(port); if(res==0) cout<<"port est encore ferme."<<endl; else cout<<"port ouvert."<<endl; //--- attente de messages cout<<"Attente de message .."<<endl; midi.Attente_Message(); cout<<"Messages recus."<<endl; //--- on affiche les messages recus dans vector<vector<unsigned char>> midi.L_message for(auto message : midi.L_message) // analyse chacun des messages midi entrant. Rem: en general il y a 1 seul message. { int port_in=(int)message[0]; // numero de port entrant message.erase(message.begin()); // enleve le 1er octet. Il reste le message midi standard cout<<"Message recu sur le port="<<port_in<<": "<<flush; for(int i=0;i<message.size();i++) cout<<(int)message[i]<<", "<<flush; cout<<endl; } //--- ferme port midi midi.Ferme_port_midi_in(port); }
//===== Programme test_midi_out.cc ========== #include <iostream> using namespace std; #include "midi.h" int main() { Midi midi; //--- ouvre port midi out int port = 0; int res = midi.Initialise_port_midi_out(port); if(res==0) { cout<<"port est encore ferme."<<endl; exit(1); } else cout<<"port ouvert."<<endl; //---- envoie message: 144, 60, 50 vector<unsigned char> message; message.push_back(144); message.push_back(60); message.push_back(50); midi.Envoi_Message(port, message); cout<<"J’ai envoye le message 144,60,50 sur le port "<<port<<endl; //-- ferme les ports midi ouverts midi.Ferme_port_midi_out(port); }
#=== Fichier Makefile LIBR= -lm -lpthread -lsndio -std=c++11 CC =g++ -std=c++11 #========================================== OBJETS_MIDI_O= test_midi_out.o midi.o midi.o : midi.cc midi.h $(CC) $(CFLAGS) -c $*.cc -o $@ test_midi_out.o : test_midi_out.cc bib_fred.h $(CC) $(CFLAGS) -c $*.cc -o $@ test_midi_out: $(OBJETS_MIDI_O) $(CC) -o test_midi_out $(OBJETS_MIDI_O) $(LIBR) #========================================== OBJETS_MIDI_I= test_midi_in.o midi.o midi.o : midi.cc midi.h $(CC) $(CFLAGS) -c $*.cc -o $@ test_midi_in.o : test_midi_in.cc bib_fred.h $(CC) $(CFLAGS) -c $*.cc -o $@ test_midi_in: $(OBJETS_MIDI_I) $(CC) -o test_midi_in $(OBJETS_MIDI_I) $(LIBR) #========================== all : test_midi_out test_midi_in
midisyn /home/faure/alex_ratchov/patches/midisyn.conf
//===== Programme gamme.cc ========== #include <iostream> using namespace std; #include "midi.h" int main() { Midi midi; //--- ouvre port midi out int port = 0; int res = midi.Initialise_port_midi_out(port); if(res==0) { cout<<"port est encore ferme."<<endl; exit(1); } else cout<<"port ouvert."<<endl; //..... int ch = 0; // canal int inst = 0; // instrument, 0: piano midi.Program_Change(port, ch, inst);// associe l’instrument inst au canal ch for(int key=60; key<=72; key++) //montee de la gamme chromatique { //....... joue une note midi .......... int vol =100; cout<<"joue note "<<key<<endl; midi.Joue_note(port, ch, key, vol); // message pour jouer une note, touche key midi.Sleep(200); // attente en ms //.... eteind une note midi ......... midi.Eteind_note(port, ch, key); // message pour eteindre la touche key } //-- ferme les ports midi ouverts midi.Ferme_port_midi_out(port); }
#====== Fichier Makefile==================================== OBJETS_MIDI_G= gamme.o midi.o midi.o : midi.cc midi.h $(CC) $(CFLAGS) -c $*.cc -o $@ gamme.o : gamme.cc $(CC) $(CFLAGS) -c $*.cc -o $@ gamme: $(OBJETS_MIDI_G) $(CC) -o gamme $(OBJETS_MIDI_G) $(LIBR)
code program_change | 0 | 1 | 2 | 3 | 4 | 33 | 73 | 74 | 75 | 76 | 77 |
instrument | piano | guitare | guitare | guitare | guitare | bass | flute | flute | flute | flute | flute |
instrument: | kick | stick | snare1 | snare2 | hihatc | hihatf | hihato | crash1 | ride1_bell | ride1 | splash | crash2 | sqr | sqr |
key: | 36 | 37 | 38 | 40 | 42 | 44 | 46 | 49 | 51 | 53 | 55 | 57 | 67 | 68 |
//===== Programme gamme.cc ========== #include <iostream> using namespace std; #include "midi.h" int main() { Midi midi; //--- ouvre port midi out int port = 0; int res = midi.Initialise_port_midi_out(port); if(res==0) { cout<<"port est encore ferme."<<endl; exit(1); } else cout<<"port ouvert."<<endl; //..... int ch = 0; // canal int inst = 0; // instrument, 0: piano midi.Program_Change(port, ch, inst);// associe l’instrument inst au canal ch for(int key=60; key<=72; key++) //montee de la gamme chromatique { //....... joue une note midi .......... int vol =100; cout<<"joue note "<<key<<endl; midi.Joue_note(port, ch, key, vol); //... ride midi.Joue_note(port, 9, 53, vol); midi.Sleep(200); // attente en ms //... stick midi.Joue_note(port, 9, 37, vol); midi.Sleep(200); // attente en ms //.... eteind une note midi ......... midi.Eteind_note(port, ch, key); } //... splash midi.Joue_note(port, 9, 55, 100); //-- ferme les ports midi ouverts midi.Ferme_port_midi_out(port); }
//===== Programme reception_notes.cc ========== #include <iostream> using namespace std; #include "midi.h" int main() { Midi midi; //--- ouvre un port midi en entree int port=0; // numero de port int res = midi.Initialise_port_midi_in(port); if(res==0) cout<<"port est encore ferme."<<endl; else cout<<"port ouvert."<<endl; //--- attente de messages midi.Attente_Message(); //---analyse des messages recus for(auto message : midi.L_message) { int port_in=(int)message[0]; // numero de port entrant message.erase(message.begin()); // enleve le 1er octet. Il reste le message midi standard if(((int)message[0])/16 == 0x9 && ((int)message[2]) > 0 ) // note on avec vel>0 { int ch=(int)message[0]-0x90; int key=(int)message[1]; int vel=(int)message[2]; cout<<"Note on recue : port="<<port_in<<" canal="<<ch<<" key="<<key<<" vel="<<vel<<endl; } else if(((int)message[0])/16==0x8 || (((int)message[0])/16 == 0x9 && ((int)message[2]) == 0) ) // note off { int ch=(int)message[0]; if(ch/16==0x8) ch-= 0x80; else if(ch/16==0x9) ch-= 0x90; int key=(int)message[1]; int vel=(int)message[2]; cout<<"Note off recue : port="<<port_in<<" canal="<<ch<<" key="<<key<<" vel="<<vel<<endl; } } //--- ferme port midi midi.Ferme_port_midi_in(port); }
#========================================== OBJETS_MIDI_R= reception_notes.o midi.o midi.o : midi.cc midi.h $(CC) $(CFLAGS) -c $*.cc -o $@ reception_notes.o : reception_notes.cc $(CC) $(CFLAGS) -c $*.cc -o $@ reception_notes: $(OBJETS_MIDI_R) $(CC) -o reception_notes $(OBJETS_MIDI_R) $(LIBR) #========================== all : reception_notes
signification et nombres d’octets à suivre | |||
Messages standard | |||
x8c | Note est éteinte sur un canal | note: | durée de l’extinction, 0:lent |
x9c | Note est jouée sur canal | note | intensité. ( : éteind) |
xAc | Aftertouch sur canal (vibrato sur une note) | note | force du vibrato |
xBc | Control Change sur canal (paramétrage d’un canal) cf détails en 27.1.7. | type | valeur |
xCc | Program Change sur canal (changement d’instrument sur un canal) | instrument | - |
xDc | Canal pressure sur canal (vibrato sur un canal) | vibrato | - |
xEc | Pitch Wheel Change (glissando sur un canal) décale de . |
signification | |||
xFF | Méta-évènement. cf Section 27.1.8 | type | Lenght (+sieurs octets) |
signification | |||
xF0 | System Exclusive Message (SysEx) | ||
xF7 |
signification | |
xF8 | Timing Clock: Envoyé 24 fois par noire en cas de synchronisation |
xFA | Start: Démarre une séquence. Il est possible souvent d’autoriser un clavier à déclencher le démarrage d’une séquence (typiquement pour un enregistrement). |
xFB | Continue: Reprend une séquence à l’endroit où elle avait été arrêtée. |
xFC | Stop: Arrête la séquence en cours. |
xFE | En cas de premier envoi, ce message doit être répété avec un délai maximum de 0,3 seconde, sinon la connexion sera réputée coupée, et tous les voix éteintes |
xFF | Reset Réinitialisation |
type (en hexa) | signification |
00 | Sequence Number |
01 | Text Event |
02 | Copyright Notice |
03 | Sequence Name |
04 | Instrument Name |
05 | Lyric/Display |
06 | Marker text |
07 | Cue point |
08 | Program Name |
09 | Peripheric Name |
20 | MIDI channel prefix assignment |
End of track (cf + haut) | |
51 | Tempo Setting |
84 (dec) | SMPTE Offset |
88(dec) | Time Signature |
89 (dec) | Key Signature |
127 (dec) | Sequencer Specific Event |
`pkg-config --cflags --libs opencv`
g++ main.cpp -o main -g -std=c++11 `pkg-config --cflags --libs opencv`
#include <iostream> using namespace std; #include <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; //========================= int main() { //..... Lecture des images -> img Mat img= imread("Image.jpg"); //...... Ecriture d’une image: img -> fichier Image2.jpg imwrite("Image2.jpg", img); //..... Lecture d’un pixel int x=img.cols/2; // selectionne point (x,y) au centre de l’image int y=img.rows/2; Vec3b p= img.at<Vec3b>(x,y); cout << "La valeur du pixel en x="<<x<<", y="<<y<<" est (B,G,R): (" << (int)p[0] << "," <<(int)p[1] << "," << (int)p[2] << ")" << endl; //..... dessin de l’image imshow("Image", img); //..... Attend qu’une touche soit appuyee. int c = waitKey(0); // rem: montre le dessin. Renvoit le code de la touche. On peut mettre une duree t en ms. ex: 2000 }
#include <iostream> using namespace std; #include <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; //------------------------------- Mat img, image, roi; int etat_select = 0;// 0: selection pas faite, 1: selection en cours, 2: selection faite Rect selection; // taille de la selection Point origin; // point de depart de la selection //---- fonction appelee si la souris est actionnee static void onMouse( int event, int x, int y, int, void* ) { // cout<<"event="<<event<<" x="<<x<<" y="<<y<<endl; //--- si action du clic souris switch( event ) { case 1: // clic gauche down if(etat_select==0) { origin = Point(x,y); selection = Rect(x,y,0,0); etat_select = 1; } break; case 4: // clic gauche up if( etat_select==1 && selection.width > 0 && selection.height > 0 ) { etat_select =2; // selection finie bitwise_not(roi, roi); // inversion de roi (dans image) imshow("Image", roi); } break; case 2: //clic droit down if(etat_select==2) { etat_select = 0; imshow("Image", img); } } //--- si deplacement souris, traitement de l’image if( etat_select == 1 ) { selection.x = MIN(x, origin.x); selection.y = MIN(y, origin.y); selection.width = std::abs(x - origin.x); selection.height = std::abs(y - origin.y); selection &= Rect(0, 0, img.cols, img.rows); // pour ne pas depasser image totale if(selection.width > 0 && selection.height > 0 ) { img.copyTo(image); roi = Mat(image, selection); // la matrice roi est une selection de image bitwise_not(roi, roi); // inversion de roi (dans image) imshow("Image", image); // montre image avec sa selection inversee } } } //========================= int main() { //..... Lecture des images img= imread("M2.png"); //..... Affiche l’image a l’ecran namedWindow( "Image", 1 ); setMouseCallback( "Image", onMouse, 0 ); // associe la fonction de lecture de la souris imshow("Image", img); waitKey(0); }
#include <iostream> #include <string> #include <sstream> using namespace std; #include "opencv2/core.hpp" #include "opencv2/highgui.hpp" using namespace cv; //------------------------------------- int main() { //.... ouverture du fichier video ou webcam String nom = "video_pendule.mp4"; // fichier video VideoCapture cap; cap.open(nom); //cap.open(0);// ouvre la webcam. if(!cap.isOpened()) // si erreur d’ouverture return -1; //...ouverture d’un fichier video en ecriture String nom2= "video_pendule2.avi"; // fichier video Size frameSize(static_cast<int>(cap.get(CV_CAP_PROP_FRAME_WIDTH)), static_cast<int>(cap.get(CV_CAP_PROP_FRAME_HEIGHT))); VideoWriter out (nom2, CV_FOURCC(’P’,’I’,’M’,’1’), 20, frameSize, true); //initialize the VideoWriter object if ( !out.isOpened() ) return -1; //.... boucle infinie while(true) { Mat img; cap >> img; // extrait la prochaine image imshow("Video", img); // dessin de img dans la fenetre Video out.write(img); // ecrit l’image dans fichier if(waitKey(30) >= 0) break; // Montre dessin. Attente de 30 ms et arret si touche appuyee } cap.release(); //libere la memoire allouee }
#include <iostream> using namespace std; #include <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> //#include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" //#include "opencv2/highgui.hpp" using namespace cv; //========================= int main() { //------------------ Mat img= imread("objet_bleu.jpg"); //imshow("img", img); //------ convertit format RGB -> format HSV Mat img_hsv; cvtColor(img, img_hsv, COLOR_BGR2HSV); // img -> img_hsv //imshow("img_hsv", img_hsv); //-------- seuillage pour extraire le bleu -> masque Scalar inf = Scalar(60,100,100); // limite inf du bleu (code HSV entre 0 et 255) Scalar sup = Scalar(180,255,255); // limite sup du bleu Mat mask; inRange(img_hsv, inf, sup, mask); // img_hsv -> matrice mask : contient 0 (pas bleu) ou 1 (bleu) //imshow("mask", mask); // ----- on applique le masque sur l’image Mat img2; bitwise_and(img, img, img2, mask); // img, mask -> img2 //imshow("img2", img2); //--------On lisse l’image Mat img3; medianBlur(img2, img3, 5); // lisse l’image sur taille 5. img2 -> img3 imshow("img3", img3); //..... Attend qu’une touche soit appuyee. waitKey(0); }
#include "opencv2/video/tracking.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <ctype.h> using namespace cv; using namespace std; //------------------------------- Mat image; bool backprojMode = false; // true: si on montre l'image seuillee bool showHist = false; // true: on montre l'histogramme bool selectObject = false; // true: si on est en train de selectionner int trackObject = 0; //0: pas de selection faite. -1: selection faite mais à traiter. 1: selection faite et traitee. Rect selection; // taille de la selection Point origin; // point de depart de la selection //---- Si l'utilisateur selection un rectangle -> selection et le flag trackObject =1. static void onMouse( int event, int x, int y, int, void* ) { // cout<<"event="<<event<<" x="<<x<<" y="<<y<<endl; if( selectObject ) { selection.x = MIN(x, origin.x); selection.y = MIN(y, origin.y); selection.width = std::abs(x - origin.x); selection.height = std::abs(y - origin.y); selection &= Rect(0, 0, image.cols, image.rows); // pour ne pas depasser image totale } switch( event ) { cout<<"event="<<event<<endl; case CV_EVENT_LBUTTONDOWN: // coin de depart origin = Point(x,y); selection = Rect(x,y,0,0); selectObject = true; break; case CV_EVENT_LBUTTONUP: selectObject = false; if( selection.width > 0 && selection.height > 0 ) trackObject = -1; break; } } //------------------------------- static void help() { cout << "\nThis is a demo that shows mean-shift based tracking\n" "You select a color objects such as your face and it tracks it.\n" "Usage: \n" " ./camshiftdemo \n"; cout << "\n\nHot keys: \n" "\tESC - quit the program\n" "\tc - stop the tracking\n" "\tb - switch to/from backprojection view\n" "\th - show/hide object histogram\n" "\tp - pause video\n" "To initialize tracking, select the object with mouse\n"; } ///------------------------------- int main( int argc, const char** argv ) { help(); VideoCapture cap; Rect trackWindow; int hsize = 16; // pour histogramme float hranges[] = {0,180}; const float* phranges = hranges; String videoFile= "pendule_jaune.mp4"; // fichier video // cap.open(videoFile); // ouvre le fichier video cap.open(0); // ouvre camera if( !cap.isOpened() ) { cout << "***Could not initialize capturing...***\n"; return -1; } //... initialise les fenetres namedWindow( "Histogram", 0 ); namedWindow( "CamShift Demo", 0 ); setMouseCallback( "CamShift Demo", onMouse, 0 ); // associe la fonction de lecture de la souris //.... pose les sliders int vmin = 10, vmax = 256, smin = 30; createTrackbar( "Vmin", "CamShift Demo", &vmin, 256, 0 ); createTrackbar( "Vmax", "CamShift Demo", &vmax, 256, 0 ); createTrackbar( "Smin", "CamShift Demo", &smin, 256, 0 ); Mat frame, hsv, hue, mask, hist, histimg = Mat::zeros(200, 320, CV_8UC3), backproj; bool paused = false; //------ boucle infinie ---------- for(;;) { if( !paused ) { cap >> frame; if( frame.empty() ) break; } frame.copyTo(image); // -> image if( !paused ) { cvtColor(image, hsv, COLOR_BGR2HSV); // convertit -> hsv if( trackObject ) { int _vmin = vmin, _vmax = vmax; // seuillage -> mask (fenetre de 0 et 1) inRange(hsv, Scalar(0, smin, MIN(_vmin,_vmax)), Scalar(180, 256, MAX(_vmin, _vmax)), mask); //imshow( "mask", mask); // Mix the specified channels int ch[] = {0, 0}; hue.create(hsv.size(), hsv.depth()); // -> hue: nouvelle fenetre vide de meme taille et type mixChannels(&hsv, 1, &hue, 1, ch, 1); // -> copie hsv dans hue // on traite la selection -> histogramme if( trackObject < 0 ) { cout<<"ici"<<endl; // Create images based on selected regions of interest (roi) Mat roi(hue, selection), maskroi(mask, selection); // imshow( "hue", hue); //imshow( "mask", mask); //waitKey(0); // Compute the histogram and normalize it -> tableau hist calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges); normalize(hist, hist, 0, 255, CV_MINMAX); trackWindow = selection; trackObject = 1; histimg = Scalar::all(0); int binW = histimg.cols / hsize; Mat buf(1, hsize, CV_8UC3); for( int i = 0; i < hsize; i++ ) buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255); cvtColor(buf, buf, CV_HSV2BGR); // dessin des rectangles de l'histogramme sur la fenetre histimg for( int i = 0; i < hsize; i++ ) { int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255); rectangle( histimg, Point(i*binW,histimg.rows), Point((i+1)*binW,histimg.rows - val), Scalar(buf.at<Vec3b>(i)), -1, 8 ); } } // Compute the histogram backprojection calcBackProject(&hue, 1, 0, hist, backproj, &phranges); // -> backproj backproj &= mask; // ameliore backproj //... trackwindow, backproj -> trackBox RotatedRect trackBox = CamShift(backproj, trackWindow, TermCriteria( CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1 )); // Check if the area of trackingRect is too small if( trackWindow.area() <= 1 ) { // Use an offset value to make sure the trackingRect has a minimum size int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5)/6; trackWindow = Rect(trackWindow.x - r, trackWindow.y - r, trackWindow.x + r, trackWindow.y + r) & Rect(0, 0, cols, rows); } if( backprojMode ) cvtColor( backproj, image, COLOR_GRAY2BGR ); // draw rotated rectangle trackBox Point2f rect_points[4]; trackBox.points( rect_points ); RNG rng(12345); Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); for( int j = 0; j < 4; j++ ) line( image, rect_points[j], rect_points[(j+1)%4], color, 1, 8 ); // Draw the ellipse on top of the image ellipse( image, trackBox, Scalar(0,0,255), 3, CV_AA ); } } else if( trackObject < 0 ) paused = false; // Apply the 'negative' effect on the selected region of interest if( selectObject && selection.width > 0 && selection.height > 0 ) { Mat roi(image, selection); bitwise_not(roi, roi); } imshow( "CamShift Demo", image ); imshow( "Histogram", histimg ); char c = (char)waitKey(10); if( c == 27 ) // esc. break; switch(c) { case 'b': backprojMode = !backprojMode; break; case 'c': trackObject = 0; histimg = Scalar::all(0); break; case 'h': showHist = !showHist; if( !showHist ) destroyWindow( "Histogram" ); else namedWindow( "Histogram", 1 ); break; case 'p': paused = !paused; break; default: ; } } return 0; }
#include <iostream>using namespace std;double somme(double a,double b){return a+b;}int main(){double a=2, b=3.1;cout<<" a="<<a<<", b="<<b<<", a+b="<<a+b<<endl;}
#include <math.h>extern "C"{//-------------int f1(int x){return x+2;}//-------------char* f2(char*s){char *u;u = new char[3];u[0]=s[0];u[1]=s[1];u[2]=’\0’; // fin de chainereturn u;}}
<!DOCTYPE html><html><body><p>Entrer nombre x :</p><input id="n"><button type="button" onclick="F()">Submit</button><h3>resultat f1(x)=x+2:</h3><p id="zone1"></p><h3>resultat f2(x): 2 premiers caracteres de x sont:</h3><p id="zone2"></p><script src="test.js"></script><script>function F(){var x = document.getElementById("n").value; // recupere entree (string)//........f1 = Module.cwrap(’f1’, ’number’, [’number’]); // declaration de la fonction qui est definie dans test.jsvar y1 = f1(x);document.getElementById("zone1").innerHTML = y1; // envoie resultat (string)//........f2 = Module.cwrap(’f2’, ’string’, [’string’]);var y2 = f2(x);document.getElementById("zone2").innerHTML = y2; // envoie resultat (string)}</script></body></html>
#include <emscripten.h>//=========================extern "C"{int f(float factor, float *arr, int length){for (int i = 0; i < length; i++){arr[i] = factor * arr[i];}return 0;}}
<!DOCTYPE html><html><body><button type="button" onclick="F()">Submit</button><script src="test_array.js"></script><script>//---------------------------function Tableau_to_Pointeur(data){var nDataBytes = data.length * data.BYTES_PER_ELEMENT; // data byte sizevar dataPtr = Module._malloc(nDataBytes); // allocate memory on Emscripten heap, and get pointer//.......... Copy data to Emscripten heap (directly accessed from Module.HEAPU8)var dataHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, nDataBytes);dataHeap.set(new Uint8Array(data.buffer));return dataHeap;}//--------------------function Pointeur_to_Tableau(dataHeap, N){var data2 = new Float32Array(dataHeap.buffer, dataHeap.byteOffset, N);Module._free(dataHeap.byteOffset); // Free memoryreturn data2;}//--------------------function F(){var data = new Float32Array([1, 2, 3, 4, 5]);//---- print arrayvar txt =’’;for (x in data){txt+= data[x]+","+" ";}document.getElementById("zone1").innerHTML= txt;//--- appel fonction c++ avec un tableauvar p = Tableau_to_Pointeur(data);f = Module.cwrap(’f’, ’number’, [’number’, ’number’, ’number’]); // import fonction c++f(2, p.byteOffset , data.length); // appel fonction c++var data2 = Pointeur_to_Tableau(p, data.length);//---- print arrayvar txt2 =’’;for (x in data2){txt2 += data2[x]+","+" ";}document.getElementById("zone2").innerHTML= txt2;}</script><h3>tableau avant appel fonction c++</h3><p id="zone1"></p><h3>tableau apres appel fonction c++</h3><p id="zone2"></p></body></html>
#include <math.h>#include <sstream>#include <string>#include <iostream>using namespace std;#include <vector>#include <string.h>//=======================================// Decompose la chaine "| .. | ..|" en sous chaines des caractères entre les ’|’ =delimvector<string> Decompose(string ligne,char delim){vector<string> instructions;while(ligne.find(delim)!=string::npos) // il reste une instruction{auto pos= ligne.find(delim);string ligne2=ligne.substr(0,pos);//.................instructions.push_back(ligne2);ligne=ligne.substr(pos+1);// cout<<" I="<<ligne2<<flush;}if(ligne.size()>0){// cout<<" I="<<ligne<<flush;instructions.push_back(ligne);}return instructions;}//=========================extern "C"{const char* f(char*s){//--- parse la chaine en entree:vector<string> vs=Decompose(string(s),’%’);//--- lecture des donneesdouble x = stod(vs[0]);string m=vs[1];//--- traitementdouble y=x+2;string m2="Salut "+m;//----fabrique la chaine de sortiestring str_out;str_out = to_string(y) + “%” + m2; // on choisit le signe % pour separer les donnéeschar * s_out = new char [str_out.length()+1];strcpy(s_out, str_out.c_str());return s_out;}}//===========================int main(){//... test ...char s[]="3.14%fred faure";const char*u = f(s);}
emcc test.cc -std=c++11 -O2 -o test.js -s EXPORTED_FUNCTIONS="[’_f’]"
<!DOCTYPE html><html><body><p>Entrer nombre x :</p><input type="number" id="x"><p>Entrer Nom :</p><input id="m"><button type="button" onclick="F()">Submit</button><script src="test.js"></script><script>function F(){var x = document.getElementById("x").value;var m = document.getElementById("m").value;var s = x.toString() + "%" + m.toString() ;//........f = Module.cwrap(’f’, ’string’, [’string’])var u = f(s);document.getElementById("zone2").innerHTML = "debug";var tu = u.split("%"); // on choisit le signe % pour separer les donnéesdocument.getElementById("zone1").innerHTML = "x+2=" + tu[0];document.getElementById("zone2").innerHTML = tu[1];}</script><h3>resultat 1</h3><p id="zone1"></p><h3>resultat 2</h3><p id="zone2"></p></body></html>
g++ test.cc -std=c++11 -O2 -o test
// -*- mode:C++ ; compile-command: "emcc test.cc -std=c++11 -O2 -o test.js -s EXPORTED_FUNCTIONS="[’_f’]"" -*-#include <emscripten.h>//=========================extern "C"{void f(){//.. on passe du code js dans une chaine de caracterestring code =" var y=3; document.getElementById(\"zone1\").innerHTML = y;";emscripten_run_script(code.c_str());// on passe du code js dans (..)EM_ASM(alert(’hello world!’););// transfert de variables c++ -> js. Elles sont recuperees par $0,$1 etcdouble x0=1.2, x1=4.3;EM_ASM_(var x0= $0; var x1 = $1; document.getElementById("zone2").innerHTML = "x0 x1 = " + x0 + x1;, x0, x1);// transfert de variables INT js -> c++int x = EM_ASM_INT({var x=3;return x;}, 0);//.. affiche le contenustring s = "document.getElementById(\"zone3\").innerHTML = \"" + to_string(x) + "\";";emscripten_run_script(s.c_str());// transfert de variables DOUBLE js -> c++double x = EM_ASM_DOUBLE({var x=3.14;return x;}, 0);//.. affiche le contenustring s = "document.getElementById(\"zone4\").innerHTML = \"" + to_string(x) + "\";";emscripten_run_script(s.c_str());}}
<!DOCTYPE html><html><body><button type="button" onclick="F()">Submit</button><script src="test.js"></script><script>function F(){f = Module.cwrap(’f’, ’string’, [’string’])f();}</script><h3>resultat 1</h3><p id="zone1"></p><h3>resultat 2</h3><p id="zone2"></p><p id="zone3"></p><p id="zone4"></p></body></html>
// -*- mode:C++ ; compile-command: "emcc test.cc -std=c++11 -O2 -o test.js -s EXPORTED_FUNCTIONS="[’_f’]" --preload-file file.txt " -*-#include <fstream>using namespace std;#include <emscripten.h>//=========================extern "C"{void f(){//... lecture depuis fichierifstream g("file.txt");string res;g>>res;//.. affiche le contenustring s = "document.getElementById(\"zone1\").innerHTML = \"" + res + "\";";emscripten_run_script(s.c_str());}}
<!DOCTYPE html><html><body><button type="button" onclick="F()">Submit</button><script src="test.js"></script><script>function F(){f = Module.cwrap(’f’)f();}</script><p id="zone1"></p></body></html>
// -*- mode:C++ ; compile-command: "emcc main.cc -std=c++11 -O2 -o index.html" -*- /* Execution: ---------- python -m SimpleHTTPServer 8000 google-chrome http://localhost:8000/index.html */ #include <iostream> using namespace std; #include <emscripten/html5.h> //------------------- void Loop(void * data) { cout<<"Call of Loop()"<<endl; } //------------------- int main() { void *userData; long id = emscripten_set_interval(Loop, 1000, userData); }
class Com;extern Com *p_com; // pointeur sur l’objet (declare dans .cc)extern mutex mtx;
- Si un widget est activé (changé), le process "com" change les variables du main avec une protection prealable de type mutex.
- depuis le process "main", on appelle explicitement p_com->Met_a_jour() pour que l’affichage de "com" corresponde aux variables de "main".
- optionnellement, le process "com" appelle Met_a_jour() de facon periodique (tous les 0.1 sec), pour eviter cet appel explicite.
- Dans le programme "main", avant/apres d’acceder aux variables partagees, il faut mettre/ enlever le mutex mtx: mtx.lock(); mtx.unlock();