ROOT C++を使ってC++プログラミング学習

その買うを、もっとハッピーに。|ハピタス

ROOT C++でC++プログラミングを学習する。

スポンサーリンク

g++

先ず、0~9までの数字をソートするコードを書く。

#include <iostream> 
#include <algorithm> 
  
using namespace std; 
  
void dsp(int n[]) 
{ 
    for(int i = 0; i < 10; ++i) 
        cout << n[i] << " "; 
} 
  
int main() 
{ 
    int n[10]= {4,2,7,9,6,1,8,3,0,5}; 
    cout << "\n The array to sort is : "; 
    dsp(n); 
  
    sort(n, n+10); 
  
    cout << "\n\n The array sorted is : "; 
    dsp(n); 
  
    return 0; 
}
Created file '/home/workspace/sort.cpp'.

gccでコードをコンパイルする。

!g++ -O3 -std=c++11 sort.cpp -o sort
!./sort
 The array to sort is : 4 2 7 9 6 1 8 3 0 5 

 The array sorted is : 0 1 2 3 4 5 6 7 8 9 
スポンサーリンク

ROOT C++

上のコードは、ROOT C++で以下のように書き換えられる。

void dsp(int n[]) 
{ 
    for(int i = 0; i < 10; ++i) 
        cout << n[i] << " "; 
} 
int n[10]= {4,2,7,9,6,1,8,3,0,5}; 
cout << "\n The array to sort is : "; 
dsp(n); 

sort(n, n+10); 

cout << "\n\n The array sorted is : "; 
dsp(n);
 The array to sort is : 4 2 7 9 6 1 8 3 0 5 

 The array sorted is : 0 1 2 3 4 5 6 7 8 9 

ROOT C++を使うとコードをかなり簡略化できる。コードを書き換える時は非常に便利である。

void dsp1(float a[]) 
{ 
    for(int i = 0; i < 5; ++i) 
        cout << a[i] << " "; 
} 

float a[5]= {1.4,4.5,0.5,2.7,1.1}; 
cout << "\n The array to sort is : "; 
dsp1(a); 

sort(a, a+5); 

cout << "\n\n The array sorted is : "; 
dsp1(a);
 The array to sort is : 1.4 4.5 0.5 2.7 1.1 

 The array sorted is : 0.5 1.1 1.4 2.7 4.5 

文字列の文字数を数えるプログラムを書く

string s = "bakatare";
const int size=s.length();
cout << "Number of characters are: " << size << endl;
Number of characters are: 8

2つの配列の積を求めるコードを書く。

int ArrayProduct(int m[], int n) 
{ 
	return accumulate(m, m + n, 1, multiplies<int>()); 
} 

int m1[] = {123,321}; 

int n = sizeof(m1) / sizeof(m1[0]); 

cout <<"123x321 is:" <<ArrayProduct(m1, n);
123x321 is:39483

ROOT C++はC++初歩学習用の良いツールになりそうである。

スポンサーリンク
スポンサーリンク