仮想計算機構

IT業界と無縁な派遣社員のブログ

【Ubuntu】【C++】Boostをダウンロードして使ってみた

ダウンロード

現時点(2022/08/27)での最新版である1.80.0をダウンロードします。
https://www.boost.org/users/history/version_1_80_0.html
ダウンロードが終わったらディレクトリを指定して解凍します。

tar --bzip2 -xf /path/to/boost_1_80_0.tar.bz2

サンプル

解凍が終わったらビルドなどは置いておいて、とりあえずサンプルプログラムを動かしていきます。

サンプル1:lambda

プログラム

受け取った数字を三倍して表示するプログラムです。

#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>

int main(){
  using namespace boost::lambda;
  typedef std::istream_iterator<int> in;

  std::for_each(in(std::cin),
                in(),
                std::cout << (_1 * 3) <<" ");
}
実行結果
$ c++ -I path/to/boost_1_80_0 example.cpp -o example
$ echo 1 2 3 | ./example
3 6 9

サンプル2:regex

正規表現を用いてメールの件名を抽出するプログラムです。

プログラム
#include <boost/regex.hpp>
#include <iostream>
#include <string>

int main(){
  std::string line;
  boost::regex pat("^Subject: (Re: |Aw: )*(.*)");

  while(std::cin){
    std::getline(std::cin,line);
    boost::smatch matches;
    if(boost::regex_match(line, matches, pat))
      std::cout << matches[2] << std::endl;
  }
}
使用データ:email.txt

以下のようなテキトーなデータを準備しました。

Subject: Hello,Mike!
I am riverta.
This is Subject: .
Subject: Goodbye Mike!
実行結果
$ c++ -I path/to/boost_1_80_0 example.cpp -o example
$ cat email.txt | ./example
Hello,Mike!
Goodbye Mike!

サンプル3:all_of

predicate を各要素に適用し、すべての要素について成り立つかどうか判定するプログラムです。元のサンプルを多少編集しております。

プログラム
#include <iostream>
#include <vector>
#include <boost/algorithm/cxx11/all_of.hpp>

bool isOdd(int i){ return i%2==1; }
bool lessThan10(int i){ return i<10; }
template<class T>
void print(const T& value){std::cout << value << std::endl;}

int main(){
  using namespace boost::algorithm;
  std::vector<int> c = {0,1,2,3,14,15};
  print(all_of(c, isOdd));
  print(all_of(c.begin(), c.end(), lessThan10));
}
実行結果

どちらも False なので数字の 0 が表示されます。

$ c++ -I path/to/boost_1_80_0 example.cpp -o example
$./example
0
0