在用户输入上使用 Count_if

Using Count_if on user input

我想做的是创建一个函数,根据容器中列出的轨道类型计算物体的数量。由于这是在寻找某个参数,所以我使用了 count_if.

结构是这样设置的。

struct body{
    string name;
    string cartype;
    string tracktype;
    string price;
    string dayfin; 
};

代码会询问您希望算法计算哪种轨道类型,例如 DirtOval、ShortOval 等。但是,无论我做什么,我都无法 count_if 考虑我的用户输入,因此需要帮助。到目前为止,这是我的代码。

int sum;
cout << "What track type?";
getline(cin, tempStr);

for(int i = 0; i <inventory.size(); i++){
    sum = count_if(inventory.begin(), inventory.end(), tempStr);
}
cout << "There are " << sum << " number of bodies for this type of track in our inventory." << endl << endl;

您正在尝试将字符串传递给 count_if(),其中需要谓词。请改用 lambda,例如(假设 inventorybody 元素的集合):

string tempStr;
cout << "What track type?";
getline(cin, tempStr);

int sum = count_if(inventory.begin(), inventory.end(),
  [&](const body &b) { return b.tracktype == tempStr; }
);

cout << "There are " << sum << " number of bodies for this type of track in our inventory." << endl << endl;