The essence of the program: get a map, where the values are char from the passed string, and the key is the number of these values in the string
using namespace std;
map<char, int> is_merge(const string& s) {
map<char, int> sCount {};
for (auto lp : s) {
if (find_if(sCount.begin(), sCount.end(), lp) != sCount.end()) {
sCount[lp] = 1;
} else {
sCount.insert(make_pair(lp, 0));
}
}
return sCount;
}
int main()
{
string test = "aba";
map <char, int> res = is_merge(test);
for (auto lp : res) {
cout << lp.first << ":" << lp.second << endl;
}
return 0;
}
But an error occurs in the console: /usr/include/c /12/bits/predefined_ops.h:318:30: error: expression cannot be used as a function 318 | { return bool(_M_pred(*__it)); } | ~~~~~~~^~~~~~~
CodePudding user response:
std::find_if
takes a predicate not a value. Hence the error that lp
is not a callable. To find a key in a map you should use std::map::find
because it is O(logn)
compared to O(n)
for std::find
/std::find_if
(as a rule of thumb you can remember: If a container has a member function that does the same as a generic algorithm the member function is at least as effcient, often better).
However, there is not need to check if the key is present via find
. The function can be this:
map<char, int> is_merge(const string& s) {
map<char, int> sCount {};
for (auto lp : s) {
sCount[lp];
}
return sCount;
}
std::map::operator[]
already does insert an element when none is found for the given key. You don't need to do that yourself.
PS: And if you do call insert
then there is no need for std::make_pair
: sCount.insert({lp, 0});
. std::make_pair
is for when you need to deduce the type of the pair from arguments to std::make_pair
, but you don't need that here.
PPS: And if you do use std::find
you need to consider that the element type of your map is std::pair<const char, int>
, not char
.