アプリケーション開発ポータルサイト
ServerNote.NET
カテゴリー【C/C++
【C++】クラス配列の任意のメンバ変数の総和を求める
POSTED BY
2024-12-15

メンバ変数にintとstringを持つ以下のようなクラスがあるとして、

  1. #include <string>
  2.  
  3. class Test {
  4. public:
  5. int number;
  6. std::string string;
  7. Test(int n, std::string s) {
  8. number = n;
  9. string = s;
  10. }
  11. };
  12. </string>

その配列を以下のように確保したとする。

  1. #include <vector>
  2.  
  3. std::vector<test> tests = std::vector<test>();
  4.  
  5. tests.push_back(Test(1, std::string("あ")));
  6. tests.push_back(Test(2, std::string("い")));
  7. tests.push_back(Test(3, std::string("う")));
  8. tests.push_back(Test(4, std::string("え")));
  9. tests.push_back(Test(5, std::string("お")));
  10. </test></test></vector>

ここで、メンバ変数numberおよびstringの総和を求めるにはstd::accumulateを使う。

  1. #include <numeric>
  2.  
  3. int number_all = std::accumulate( tests.begin(), tests.end(), 0,
  4. []( int n, auto &c ){ return n + c.number; } );
  5.  
  6. std::string string_all = std::accumulate( tests.begin(), tests.end(), std::string(""),
  7. []( std::string s, auto &c ){ return s + c.string; } );
  8. </numeric>

第3引数には総和の初期値、第4引数に加算関数をラムダ式に定義する。なお、vectorがクラスでなく単体intやstringの配列なら第4引数(加算関数)の定義は不要であり、自動加算される。

トータルのサンプルソースは以下。

C/C++std_accumulate.cppGitHub Source
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <numeric>
  5.  
  6. class Test {
  7. public:
  8. int number;
  9. std::string string;
  10. Test(int n, std::string s) {
  11. number = n;
  12. string = s;
  13. }
  14. };
  15.  
  16. int main(void) {
  17.  
  18. std::vector<Test> tests = std::vector<Test>();
  19.  
  20. tests.push_back(Test(1, std::string("あ")));
  21. tests.push_back(Test(2, std::string("い")));
  22. tests.push_back(Test(3, std::string("う")));
  23. tests.push_back(Test(4, std::string("え")));
  24. tests.push_back(Test(5, std::string("お")));
  25.  
  26. int number_all = std::accumulate( tests.begin(), tests.end(), 0,
  27. []( int n, auto &c ){ return n + c.number; } );
  28.  
  29. std::string string_all = std::accumulate( tests.begin(), tests.end(), std::string(""),
  30. []( std::string s, auto &c ){ return s + c.string; } );
  31.  
  32. std::cout << "number_all=" << number_all << ", string_all=" << string_all << std::endl;
  33.  
  34. return 0;
  35. }

コンパイル、実行結果

  1. g++ std_accumulate.cpp
  2.  
  3. ./a.out
  4.  
  5. number_all=15, string_all=あいうえお

※本記事は当サイト管理人の個人的な備忘録です。本記事の参照又は付随ソースコード利用後にいかなる損害が発生しても当サイト及び管理人は一切責任を負いません。
※本記事内容の無断転載を禁じます。
【WEBMASTER/管理人】
自営業プログラマーです。お仕事ください!
ご連絡は以下アドレスまでお願いします★

【キーワード検索】