「C++の基礎 - クロージャ」の版間の差分

ナビゲーションに移動 検索に移動
 
194行目: 194行目:
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br><br>
== クロージャの使用例 : カスタムソート ==
以下の例では、複雑なソート条件をクロージャで実装している。 <br>
複数の条件を組み合わせたソート、値キャプチャによる設定値の保持、構造体の入力値検証している。<br>
<br>
<syntaxhighlight lang="c++">
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
struct Product {
    std::string name;
    double      price;
    int        stock;
    Product(const std::string &n, double p, int s) : name(n), price(p), stock(s) {
      // 入力値の検証
      if (p < 0) throw std::invalid_argument("価格は0以上を入力");
      if (s < 0) throw std::invalid_argument("在庫数は0以上を入力");
    }
};
int main()
{
    try {
      // 商品データの作成
      std::vector<Product> products{
          Product("商品A", 1000, 5),
          Product("商品B", 2000, 3),
          Product("商品C", 1500, 0)
      };
      // ソート条件の優先順位を設定
      bool  prioritizeStock = true;  // 在庫優先フラグ
      double minPrice        = 1200;  // 価格の閾値
      // クロージャでソート条件を定義
      auto sortCondition = [prioritizeStock, minPrice](const Product& a, const Product& b) {
          if (prioritizeStock) {
            // 在庫がある商品を優先
            if ((a.stock > 0) != (b.stock > 0)) {
                return a.stock > 0;
            }
          }
          // 価格閾値との関係で比較
          bool a_above_threshold = a.price >= minPrice;
          bool b_above_threshold = b.price >= minPrice;
          if (a_above_threshold != b_above_threshold) {
            return !a_above_threshold;  // 閾値未満を優先
          }
          // 同条件の場合は価格の安い順
          return a.price < b.price;
      };
      // ソート実行
      std::sort(products.begin(), products.end(), sortCondition);
      // 結果表示
      std::cout << "ソート結果:" << std::endl;
      for (const auto &product : products) {
          std::cout << "商品名: " << product.name << ", 価格: " << product.price << ", 在庫: " << product.stock << std::endl;
      }
    }
    catch (const std::exception &e) {
      std::cerr << "エラーが発生: " << e.what() << std::endl;
      return -1;
    }
    return 0;
}
</syntaxhighlight>
<br><br>


{{#seo:
{{#seo:

案内メニュー