Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

概要

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

実装

実装は非常に単純です。

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];
}

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away