C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources] - نسخه متنی

Herb Sutter, Andrei Alexandrescu

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید


Examples


Example:

FlagNth.
Here is the classic example from [Sutter02], which is intended to remove the third element from a container

v :

class FlagNth {
public:
FlagNth( size_t n ) : current_(0), n_(n) {}

// evaluate to true if and only if this is the n-th invocation
template<typename T>
bool operator()( const T& ) {return ++current_ == n_; }

// bad: non-const
private:
size_t current_, n_;
};

// … later …
v.erase( remove_if( v.begin(), v.end(), FlagNth(3) ) );

This is not guaranteed to remove the third element, even though that was intended. In most real-world STL implementations, it erases both the third and the sixth elements. Why? Because

remove_if is commonly implemented in terms of

find_if and

remove_copy_if , and it passes along a copy of the predicate to each of those functions, possibly after it has already itself done some work that affects the predicate's state.

Conceptually, this example is perverse because

remove_if only guarantees that it will remove all elements satisfying some criterion. It does not document the order in which elements in the range will be visited or removed, so the code is relying on an assumed, but undocumented and unsatisfied, assumption.

The correct way to remove a particular element is to iterate to it and then call

erase .


/ 521