C ++使用erase(Iterator)

时间:2017-04-22 02:46:08

标签: c++ vector erase

我有这个代码来解释我的问题:

#include <iostream>
#include <vector>

void
PrintVector (const std::vector<int> & vec)
{
  std::cout << "vector contains:";
  for (unsigned i = 0; i < vec.size (); ++i)
    std::cout << ' ' << vec[i];
  std::cout << '\n';
}

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

  for (int i = 0; i <= 10; i++) myvector.push_back (i);
  PrintVector (myvector);

  int to_delete = 9;

  for (std::vector<int>::iterator it = myvector.begin (); it != myvector.end (); ++it)
    {
      if (*it == to_delete)
        {
          std::cout << *it << " found and deleted! \n";
          myvector.erase (it);
        }
    }
  PrintVector (myvector);

  to_delete = 10;

  for (std::vector<int>::iterator it = myvector.begin (); it != myvector.end (); ++it)
    {
      if (*it == to_delete)
        {
          std::cout << *it << " found and deleted! \n";
          myvector.erase (it);
        }
    }
  PrintVector (myvector);

  return 0;
}

我有一个向量,我需要删除一些元素。我不知道他们的位置,所以我必须遍历整个矢量来寻找它们。我注意到如果删除的元素是最后一个位置,我会得到分段错误。我不知道为什么。

我得到的输出是:

vector contains: 0 1 2 3 4 5 6 7 8 9 10
9 found and deleted! 
vector contains: 0 1 2 3 4 5 6 7 8 10
10 found and deleted!         
10 found and deleted!       // QUESTION: This got repeated, why?

RUN FINISHED; Segmentation fault; core dumped; real time: 130ms; user: 0ms; system: 0ms

它应该是这样的:

vector contains: 0 1 2 3 4 5 6 7 8 9 10
9 found and deleted! 
vector contains: 0 1 2 3 4 5 6 7 8 10
10 found and deleted! 
vector contains: 0 1 2 3 4 5 6 7 8

RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms

0 个答案:

没有答案