【问题标题】:Using Count_if on user input对用户输入使用 Count_if
【发布时间】:2021-09-20 18:01:17
【问题描述】:

我要做的是创建一个函数,根据容器中列出的轨道类型计算物体的数量。由于这是在寻找某个参数,所以我使用了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;

【问题讨论】:

标签: c++ c++-standard-library


【解决方案1】:

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

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;

【讨论】:

  • 非常感谢,我之所以试图保持含糊不清是因为我知道这可以用于更多的算法,所以非常感谢你,我一直在执行整天进行心理体操来尝试解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 2015-09-07
  • 2015-11-11
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
相关资源
最近更新 更多