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);
}
};
参考
文字列操作
文字列置換(regex_replace)
string T = "ATCODER"
regex re("A|C|G|T");
string result = regex_replace(T, re, ""); // "ODR"
文字列のゼロ埋め
第2引数は(桁数) - (対象の文字の文字長)
string str = to_string(i);
s.push_back(str.insert(0, 3 - str.length(), '0'));
参考
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
}