LoginSignup
2
3

More than 5 years have passed since last update.

点構造体に配列っぽくアクセスする

Last updated at Posted at 2015-10-17

コードを書いているとふとした必要から下記のような構造体を作ることは多いと思います。

struct Point {
  int x;
  int y;
  int z;
}
使用例
int main(void){

    Point p;
    p.x = 100;
    p.y = 200;
    p.z = 300;

    cout << "p = (" << p.x << ", " << p.y << ", " << p.z << ")\n";
}
出力
p = (100, 200, 300)

このような構造体を使っているとしばしば p[0], p[1], p[2] のように配列っぽく使いたくなることがあります。そのような場合には下記のオペレータを追加するとできます。

struct Point {
    int x;
    int y;
    int z;

    // x のアドレスを基準にしたインデックス位置の参照を返す
    int& operator[] (int index) { return *(&x + index); }
};
使用例
int main(void){

    Point p;
    p.x = 100;
    p.y = 200;
    p.z = 300;

    cout << "p = (" << p.x << ", " << p.y << ", " << p.z << ")\n";

    p[0] = 10;
    p[1] = 20;
    p[2] = 30;
    cout << "p = (" << p[0] << ", " << p[1] << ", " << p[2] << ")\n";
}
出力
p = (100, 200, 300)
p = (10, 20, 30)

オペレータを追加するのが面倒 or 外部ライブラリのためできない場合には下記のようにもできます。

使用例
int main(void){

    Point p;

    int* p2 = &p.x;
    p2[0] = 10;
    p2[1] = 20;
    p2[2] = 30;

    cout << "p = (" << p.x << ", " << p.y << ", " << p.z << ")\n";
}
出力
p = (10, 20, 30)
2
3
0

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
2
3