2日目はC繋がりで、今まで触ったことのないC++
1日目の記事はこちら
[1day1lang AdventCalender] day1 C言語
環境構築
コンパイラの確認
g++がインストールされているか確認
$ g++ -v
gcc version 5.4.0 20160609
昨日と同じく、元からインストール済み
Hello World!
helloworld.cpp
# include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
改行は\n
でもいいが、endl
がスタンダードらしい
helloworld.cppをコンパイル
$ gcc helloworld.cpp
今回も出力ファイル名を -o
で名前を指定していないので、 a.out となった
$ ./a.out
Hello World!
ツリー描画
Cのソースをそのまま移植 + 出力を printf()
から cout
に変えただけのもの
tree.cpp
# include <iostream>
using namespace std;
int main() {
const char ASTER[] = "* ";
const char SPACE[] = " ";
const int EVE = 30;
int sumAster = 0;
int step = 0;
int i,j;
int trnk;
while(sumAster <= EVE) {
step ++;
sumAster += step;
}
trnk = EVE - (sumAster - step);
for (i = 1; i <= step; i++){
if (i < step) {
for (j = step; j > i; j--) cout << SPACE;
for (j = 1; j <= i; j++) cout << ASTER;
} else {
for (j = i - trnk; j >= 1; j--) cout << SPACE;
for (j = 1; j <= trnk; j++) cout << ASTER;
}
cout << endl;
}
return 0;
}
実行
$ g++ tree.cpp -o tree.out
$ ./tree.out
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * *