A predicate for stl algorithm should always be stateless

A predicate for stl algorithm should always be stateless

void test_remove_if_bug()
{
    
    
	list<int> coll = {
    
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	cout<<"coll:        ";
	std::copy(coll.begin(), coll.end(), ostream_iterator<int>(cout, " "));
	cout<<endl;

	// remove third element
	list<int>::iterator pos;
	int n = 3;
	int cur = 0;
	//ok
	// pos = remove_if(coll.begin(), coll.end(), // range
	// 				[&](const auto &e) {
    
    
	// 					return ++cur == n;
	// 				}); // remove criterion
	//bug
	pos = remove_if(coll.begin(), coll.end(), // range
					[=](const auto &e) mutable {
    
    
						return ++cur == n;
					}); // remove criterion
	coll.erase(pos, coll.end());

	cout<<"3rd removed: ";
	std::copy(coll.begin(), coll.end(), ostream_iterator<int>(cout, " "));
	cout<<endl;
}

猜你喜欢

转载自blog.csdn.net/alpha_007/article/details/114438172
今日推荐