assign を使ってみる (C++)
C++
Published: 2020-07-18

確認環境

$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

調査

test.cpp

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

int main() {
    vector<int> v;
    // 5個の要素を値10で埋める
    v.assign(5, 10);

    for (auto val : v) {
        cout << val << " ";
    }
    cout << endl;

    cout << "---" << endl;
    // 2個の要素に置き換える
    vector<int> before_v = {5, 4, 3, 2, 1};
    v.assign(before_v.begin(), before_v.begin() + 2);
    for (auto val : v) {
        cout << val << " ";
    }
    cout << endl;
}

出力結果

10 10 10 10 10
---
5 4

参考