這是我制作的代碼,但是顯示的內容不正確。請教我我需要解決什么。
#include <iostream>
#include <list>
using namespace std;
bool check(int passing){
int g;
if(g<=passing){
return false;
}else{
return true;
}
}
int main()
{
int pg;
cout<<"What is the passing grade?"<<endl;
cin>>pg;
list<int> grades = {100,90,93,95,92,98,97,99,96,94};
grades.remove_if(check);
for(int x : grades){
cout<<x<<'\t';
}
return 0;
}
uj5u.com熱心網友回復:
使用 lambda 作為謂詞,remove_if如下所示:
#include <iostream>
#include <list>
int main( )
{
std::cout << "What is the passing grade?\n";
int passingGrade { };
std::cin >> passingGrade;
std::list<int> grades { 100, 90, 93, 95, 92, 49, 50, 98, 97, 99, 11, 94 };
/*grades.remove_if( [ &passingGrade ]( const int grade ) // lambda approach
{
return ( grade < passingGrade ) ? true : false;
}
);*/
for ( auto it = grades.begin( ); it != grades.end( ); ) // for-loop approach
{
if ( *it < passingGrade )
{
it = grades.erase( it );
}
else
{
it;
}
}
for ( const int grade : grades )
{
std::cout << grade << '\t';
}
}
示例 I/O
What is the passing grade?
50
100 90 93 95 92 50 98 97 99 94
另一個樣本:
What is the passing grade?
95
100 95 98 97 99
uj5u.com熱心網友回復:
這個給你:
#include <iostream>
#include <list>
#include <functional>
bool check(int const lhs, int const rhs) {
return lhs < rhs;
}
int main() {
int pg;
std::cout << "What is the passing grade?\n";
std::cin >> pg;
std::list<int> grades{
70, 90, 79, 85, 96, 73, 99, 91, 81, 83,
99, 94, 80, 79, 85, 83, 82, 90, 84, 82,
72, 83, 76, 93, 90, 77, 82, 76, 100, 94
};
grades.remove_if(std::bind(check, std::placeholders::_1, pg));
for (auto const g : grades) {
std::cout << g << '\t';
}
return 0;
}
當被問及是否洗掉呼叫它的特定元素時,函式檢查必須回傳 true。由于 remove_if 需要一元謂詞(只能用 1 個引數呼叫的函式),我使用 std::bind 生成新的可呼叫物件,呼叫時傳遞引數 std::placeholders::_1 和 pg 來檢查 where 而不是 std::placeholders ::_1 使用來自等級的元素的副本。
讓我們用 pg = 90 來玩這個。
檢查(70, 90) -> 是 70 < 90 嗎?-> 是 -> 洗掉
檢查(90, 90) -> 90 < 90 嗎?-> 不 -> 保留
檢查(79, 90) -> 79 < 90 嗎?-> 是 -> 洗掉
檢查(85, 90) -> 85 < 90 嗎?-> 是 -> 洗掉
檢查(96, 90) -> 96 < 90 嗎?-> 不 -> 保留
我想你明白了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420226.html
標籤:
