Open5

【メモ】C++

あぷしあぷし

for文

vectorの要素をforeachで回す

vector<string> words = { "hoge", "fuga", "piyo" }
for (string w: words)
{
  // いろいろ
}
あぷしあぷし

vector操作

指定したindexにアクセス

at()または[]を使用する。

vector<bool> dp(100);
bool a1 = dp.at(0);
bool a2 = dp[0];
あぷしあぷし

map

挿入


アクセス

map<Point, int> dp;
int a = dp[{dt, dx, dy}];

Keyの存在確認

find(key)を使用する。

map<int> mm = { {1, "a"}, {2, "b"}, {3, "c"} };
int target = 2;
if (mm.find(target) != mm.end())
{
   cout << mm[target] << endl;  // "b"
}
cout << "not found" << endl;

Keyに構造体を指定する

structのオペレータ実装

オペレータ<を実装する必要がある。

struct Point
{
    int t, x, y;
    bool operator<(const Point &value) const
    {
        return tie(t, x, y) < tie(value.t, value.x, value.y);
    }
};

参考

あぷしあぷし

Set

平衡二分木で実装されているため、insert時に値が昇順で格納される。

操作

int main()
{
    set<int> st = {10, 9, 2, 3, 5, 7, 1};

    for (int s : st)
    {
        cout << s << " ";
    }
    cout << endl; // 1 2 3 5 7 9 10

    cout << *st.begin() << "," << *st.rbegin() << endl; // 1,10

    st.insert(8);
    st.erase(1);

    for (int s : st)
    {
        cout << s << " ";
    }
    cout << endl; // 2 3 5 7 8 9 10

    cout << *st.begin() << "," << *st.rbegin() << endl; // 2,10
}