cpp

std::priority_queueで自作の型を使う

cpp

方法1 operator<()を実装する 方法2 比較用の型を追加する 実行結果 参考 方法1 operator<()を実装する 以下の例のように、MyClass::operator<()を実装すればOK。 #include <iostream> #include <queue> class MyClass { public: MyClass(int num) : num_(num) {} std::string</queue></iostream>…

std::setで自作の型を使う

cpp

方法1 operator<()を実装する 方法2 比較用の型を追加する 実行結果 方法1 operator<()を実装する 以下の例のように、MyClass::operator<()を実装すればOK。 #include <set> #include <iostream> #include <string> class MyClass { public: MyClass(int num) : num_(num) {} std::s</string></iostream></set>…

C++のコンテナで最小値、最大値を得る

cpp

以下のようなfor文をよく書いてしまうが、標準ライブラリを使ってできるよという話。 #include <iostream> #include <vector> int main() { std::vector<int> v = {1, 2, 3, 4}; int min = v[0]; int max = v[0]; for(int i : v) { if(i < min) min = i; if(i > max) max = i; } pri</int></vector></iostream>…

C++のfor文

cpp

C++のいくつかあるfor文について自分でもよくわかっていなかったので改めて調べた。 次のとおり全部で4つのfor文がある。 インデックスを使ったfor イテレータを使ったfor std::for_eachを使ったfor 範囲ベースのfor(C++11以後で使える) コーディング規約…

std::unordered_setで自作の型を使う

cpp

std::unordered_setに自分で定義したクラスを入れたかったので、やってみた。 次のURLが参考になった。 https://stackoverflow.com/questions/15869066/inserting-into-an-unordered-set-with-custom-hash-function コード 主なポイントは、次の2つだった。 …