【C++】クラス,構造体は参照渡しで変数名を簡単にした

クラスを使うと変数名が長くなる

長い...

最近はクラスの勉強もかねて,数値計算のコードを半ば無理矢理にクラスを使って書いています. そこで,ちょっと問題になったのが,「クラスを使うと変数名が長くなってしまう事案」です.
例えば以下のようなコードを見てみてください.teacherには1.0を代入して,studentには099まで代入してるだけです.

#include <iostream>
#include <vector>

struct MySchool{
    double teacher;
    std::vector<std::vector<double> > student;
};

int main(){
    MySchool school;

    //これはまあ許してやろう
    school.teacher = 1.0;

    school.student.resize(10);
    for(int i = 0; i<10; i++){
        school.student[i].resize(10);
    }

    for (int i = 0; i< 10; i++){
        for(int j = 0; j< 10; j++){
            //ンンンー!イライラしてくる!!
            school.student[i][j] = 10*i + j;
            std::cout << school.student[i][j] << std::endl;
        }
    }
    return 0;
}

どうですか,流石にこれ,みにくいですよね...

ならばどうする?

いくつかの方法があり,その中でもまぁありかなというのが以下の二つ.

  • ポインタの利用
  • 参照渡し

しかし,ポインタの利用を行うとまたひどく見た目が悪い. 主要なところだけ示すと,こんな感じ

 std::vector<std::vector<double> >* student = &school.student;

    //ちゃんと元のschool.studentが変更されているか確認
    for(int i = 0; i<10; i++){
        for(int j=0; j<10; j++){
            (*student)[i][j] = 10*i + j - 1;
            std::cout << school.student[i][j] << std::endl;
        }
    }

まぁ,悪くないんだけど,やはりなんだか見にくい...

結論

ということで,参照渡しを使うしかないですね. やはりC++なんだから,参照渡し,ガンガン使っていこうよ!というお話です.

#include <iostream>
#include <vector>

struct MySchool{
    double teacher;
    std::vector<std::vector<double> > student;
};

int main(){
    MySchool school;

    //参照渡し
    double& teacher = school.teacher;
    std::vector<std::vector<double> >& student = school.student;

    //色々値とか変更してみる
    teacher = 1.0;

    student.resize(10);
    for(int i = 0; i<10; i++){
        student[i].resize(10);
    }
    for (int i = 0; i< 10; i++){
        for(int j = 0; j< 10; j++){
            student[i][j] = 10*i + j;
        }
    }

    //ちゃんと元のschool.studentが変更されているか確認
    for(int i = 0; i<10; i++){
        for(int j=0; j<10; j++){
            std::cout << school.student[i][j] << std::endl;
        }
    }
    return 0;
}