我遇到了一个奇怪的问题:std::remove_if
不能正确排列与指定谓词匹配的所有元素。例如,以下
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
struct Test {
std::string name;
double finalScore = 0;
Test( double k ) : finalScore( k ) {}
};
int main() {
std::srand( static_cast<unsigned int>( std::time( nullptr ) ) );
std::vector<Test> vec;
for ( unsigned i = 0; 50 != i; ++i ) {
vec.push_back( Test( rand() % 10 + 1 ) );
}
auto rem = std::remove_if( vec.begin(), vec.end(), []( const Test &s ) {
return s.finalScore < 5.0;
} );
std::cout << "item with below 5.0 finalScore count: "
<< ( vec.end() - rem ) << std::endl;
std::cout << "items with below 5.0 finalScore: " << std::endl;
for ( auto it = rem; vec.end() != it; ++it ) {
std::cout << it->finalScore;
if ( it->finalScore >= 5.0 ) {
std::cout << " | incorrect; should not be present after rem.";
}
std::cout << std::endl;
}
return 0;
}
产生
item with below 5.0 finalScore count: 16
items with below 5.0 finalScore:
3
9 | incorrect; should not be present after rem.
8 | incorrect; should not be present after rem.
1
5 | incorrect; should not be present after rem.
6 | incorrect; should not be present after rem.
6 | incorrect; should not be present after rem.
7 | incorrect; should not be present after rem.
3
4
4
5 | incorrect; should not be present after rem.
6 | incorrect; should not be present after rem.
2
8 | incorrect; should not be present after rem.
10 | incorrect; should not be present after rem.
问题清晰可见:有些元素,谁的finalScore
数据成员是>= 5
,这是不应该的。预期结果应该与
item with below 5.0 finalScore count: 6
items with below 5.0 finalScore:
3
1
3
4
4
2