ROOT C++でC++プログラミングを学習する。
スポンサーリンク
g++¶
#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;
}
gccでコードをコンパイルする。
!g++ -O3 -std=c++11 sort.cpp -o sort
!./sort
スポンサーリンク
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);
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);
文字列の文字数を数えるプログラムを書く
string s = "bakatare";
const int size=s.length();
cout << "Number of characters are: " << size << endl;
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);
ROOT C++はC++初歩学習用の良いツールになりそうである。
スポンサーリンク
スポンサーリンク