C++ 初級基礎:標準ライブラリ活用法

C++ の基本的な標準ライブラリ機能について、実践的な観点から整理します。

1. 入出力と基本設定

#include <bits/stdc++.h>
using namespace std;

// 入出力同期の非同期化(入出力PEED向上)
ios::sync_with_stdio(false);
cin.tie(nullptr);

C++ のストリーム(cincout)と C 言語の関数(scanfprintf)は混在を避けることが推奨されます。混在すると入出力の順序が保証されず、予期せぬ動作を引き起こす可能性があります。

2. 文字列処理(std::string

std::string は自動メモリ管理、境界チェック、イテレータサポートを提供します。

// 宣言
string s1;                 // 空文字列
string s2 = "sample";
string s3(s2);             // コピーコンストラクタ
string s4 = s2.substr(1, 4);  // offset=1, length=4 → "ampl"
string s5(5, 'x');         // "xxxxx"

// 入力:1行読み込み
string line;
getline(cin, line);
// 文字配列から string 生成
char buffer[128];
cin >> buffer;
string text(buffer);

// メソッド一覧
int len = text.length();           // 長さ取得
string combined = s1 + "," + s2;   // 結合
size_t idx = text.find("sam");     // 検索(見つからなければ string::npos)
if (idx != string::npos) {
    cout << "Hit: " << idx << '\n';
}
text.replace(1, 2, "XY");          // [1,3) を "XY" に置換
string sub = text.substr(2, 3);    // [2,5) の部分列
bool less = s1 < s2;               // 辞書順比較

// イテレーション
for (char c : text) { /* ... */ }
for (char& c : text) { c = toupper(c); }  // 参照で直接変更

文字列反転の例

string s;
getline(cin, s);
reverse(s.begin(), s.end());
cout << s << '\n';

3. ソートと並び替え

// デフォルト(昇順)
sort(arr, arr + n);              // 配列
sort(vec.begin(), vec.end());    // vector

// 降順:カスタムコンパレータ
sort(vec.begin(), vec.end(), greater<int>());

//ラムダ式による指定
sort(vec.begin(), vec.end(), [](int a, int b) { return a > b; });

// 構造体の比較演算子オーバーロード
struct Item {
    int key1, key2;
    bool operator < (const Item& o) const {
        return (key1 != o.key1) ? key1 < o.key1 : key2 < o.key2;
    }
};

4. 最大・最小・中位値探索

// 単一値比较
int m1 = min({1, 2, 3});
int m2 = max(10, 20);

// シーケンス範囲
vector<int> v = {3, 5, 1, 4};
int minval = *min_element(v.begin(), v.end());
int maxval = *max_element(v.begin(), v.end());

// k 番目に小さい要素(nth_element)
int k = 2;
nth_element(v.begin(), v.begin() + k, v.end());
// v[k] が k+1 番目に小さい要素(0-indexed)高尔夫化された状態
// 左側は v[k] 以下の要素、右側は以上の要素

5. 二分探索

前提:対象シーケンスは事前にソート済みである必要があります。

vector<int> data = {2, 4, 4, 7, 9};

// 要素の有無確認
bool exists = binary_search(data.begin(), data.end(), 4);

// 低于 or 等価 最初の位置(左BOUND)
auto lo = lower_bound(data.begin(), data.end(), 4);  // *lo == 4

// 超过 最初の位置(右BOUND)
auto hi = upper_bound(data.begin(), data.end(), 4);  // *hi == 7

// 個数計算(同値要素数)
int count = hi - lo;  // 2

// 降順シーケンスへの探索(greater を指定)
vector<int> rev = {9, 7, 4, 4, 2};
auto it = lower_bound(rev.begin(), rev.end(), 5, greater<int>());
// 5 以上で最初の要素 → *it == 4

6. 全ترتيب列生成

vector<int> perm = {1, 2, 3};
sort(perm.begin(), perm.end());
do {
    for (int x : perm) cout << x << ' ';
    cout << '\n';
} while (next_permutation(perm.begin(), perm.end()));

next_permutation は辞書順で次の並びを返し、最後まで到達すると false を返します。
prev_permutation はその逆方向です。

タグ: C++ STL String Sorting binary-search

6月3日 17:42 投稿