English 中文(简体)
定点: 放矢器无效
原标题:std::vector iterator invalidation

此前曾就这一问题提出了几个问题;我的谅解是,打电话<代码>std:vector:erase将只会使处于<<> >以下/em>地位的变压器失效。 然而,在删除一个要素之后,该职位上的主持人是否仍然有效(当然,条件是该职位在删除后没有点到<代码>end()?

我对如何实施病媒的理解似乎表明,病媒是不可阻挡的,但我并不完全相信它可能导致不明确的行为。

作为我所谈论的事例,以下守则从病媒中排除了所有奇迹。 该法典是否造成不明确的行为?

typedef std::vector<int> vectype;
vectype vec;

for (int i = 0; i < 100; ++i) vec.push_back(i);

vectype::iterator it = vec.begin();
while (it != vec.end()) {
    if (*it % 2 == 1) vec.erase(it);
    else ++it;
}

这部法典对我的机器实行罚款,但令我相信它有效。

最佳回答

在删除一个要素之后,该立场的倡导者仍然有效。

No; all of iterators at or after the iterator (s) adopted to erase

但是,<代码>erase 一位新的主持人在删除要素之后立即指出该要素(如果没有这种内容,则该要素即告终)。 你们可以利用这个使者恢复活力。


注意,这种排除奇数的具体方法效率相当低:每当你去掉一个元素时,所有因素都必须把一个位置移至病媒的左边(即O(n2)。 您可以通过erase-remove idiom(O(n))。 页: 1 前提:

bool is_odd(int x) { return (x % 2) == 1; }

然后可以通过<代码>remove_if:

vec.erase(std::remove_if(vec.begin(), vec.end(), is_odd), vec.end());
问题回答

或:

class CIsOdd
{
public:
    bool operator()(const int& x) { return (x % 2) == 1; }
};

vec.erase(std::remove_if(vec.begin(), vec.end(), CIsOdd()), vec.end());




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?