How can I change work of method Get2 using count_if()? How can I fix this variant of Get2's body?
return count_if(tck_.begin(), tck_.end(), [name](int n){return name == tck_[n].name;});
The Get1 method counts the number of all tickets at the moment. The second(Get2) method counts the number of tickets of a certain type.
struct Ts {
int id;
string name;
};
class Tc {
public:
void Push(const string& name) {
tck_.push_back({id_, name});
id_;
}
int Get1() const {
return tck_.size();
}
int Get2(const string& name) const {
//return count_if(tickets_.begin(), tickets_.end(), [name](int n){return name == tickets_[n].name;});
int counter = 0;
for (int i = 0; i < id_; i) {
if (name == tck_[i].name) {
counter ;
}
}
return counter;
}
void Invalidate(int minimum) {
for (int i = 0; i < minimum; i){
tck_.erase({tck_.begin() i});
}
}
private:
int id_ = 0;
deque<Ts> tck_;
};
Invalidate is used to revoke expired tickets — the parameter of this method specifies the number of the first current ticket. All tickets with a smaller number should be cancelled. It is assumed that the administration does not call this method if there are no necessary tickets, so the method must delete at least one ticket.
CodePudding user response:
You call count_if
with the begin()
and end()
iterators of the deque
and provide a functor, like a lambda, to do the actual comparison.
The problem you have in your lambda is that you assume it's going to be called with the index of the current element in the deque, but the lambda will actually get called with a reference to the actual element.
Example with that fixed:
#include <algorithm>
class Tc {
public:
auto Get2(const std::string& name) const {
return std::count_if(tck_.begin(), tck_.end(),
[&name](const Ts& ts) { return ts.name == name; });
// ^ ^^^^^^^^^
// | Ts&
// |
// don't copy name, take it by reference
};