LoginSignup
3
3

More than 5 years have passed since last update.

[C/C++] プリプロセス時テキストファイル読み込み

Last updated at Posted at 2018-10-21

概要

タイトルからしてゴミ記事の予感がしますが、ご覧の通り、プリプロセッサの処理時にテキストファイルを読み込む方法です。

実装

実装は非常に単純です。

int data[] = {
#include "data.csv"
};

C/C++の#includeは単なるコピペマシーンにすぎませんから、ヘッダー以外のものも読み込めます。

使い道

例えば、unsigned char型のビット列の中で1の数を数えたいとします。最も高速な方法は、長さ256のlook up tableを用意することでしょう。

@fujitanozomuさんから教えて頂いた情報によると、popcnt命令を直接呼び出すほうが速いそうです。

int count1s2(unsigned char byte) {
    static const int ones[256] =  {
        0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
        1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
        1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
        2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
        1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
        2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
        2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
        3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
    };

    return ones[(int)byte];
}

しかしこれではソースコードが醜くなり、他者が読むには適していません。そこで、このlook up tableを別ファイルに保存し、プリプロセッサで読み込んでしまいます。

int count1s2(unsigned char byte) {
    static const int ones[256] =  {
#include "ones_look_up_table"
    };

    return ones[(int)byte];
}

これで少しは?見やすくなったでしょう。

3
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3