LoginSignup
17
16

More than 5 years have passed since last update.

std::vectorから指定インデックスの要素を削除

Last updated at Posted at 2015-02-28

std::vectorで添え字から要素を削除しようとしてビビったのでメモ.

main.cpp
#include <iostream>
#include <vector>

// vectorからindex番目の要素を削除する
template<typename T>
void remove(std::vector<T>& vector, unsigned int index)
{
    vector.erase(vector.begin() + index);
}

int main()
{
    std::vector<int> v;

    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    std::cout << v[0] << v[1] << v[2] << std::endl;
    // "123"が出力される

    remove(v, 1);
    std::cout << v[0] << v[1] << std::endl;
    // "13"が出力される

    return 0;
}

iteratorに足し算できるところは, 美しいとは思うのですが, 本当にこれしか方法ないのかな...?

17
16
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
16