HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Counting the total number of characters in an std::set<std::string>

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
totalstdnumberthecountingcharactersstringset

Problem

I have a std::set and I need to know the total number of characters (sum of all strings length):

static size_t SumLength(size_t value, const std::string &str)
{
    return str.length() + value;
}

size_t TotalLength(std::set &stringSet)
{
   return std::accumulate(stringSet.begin(), stringSet.end(), 0, SumLength);
}


What do you think of this approach?

Solution

You should make the parameter to TotalLength const, so you can use it on constant sets. Since TotalLength does not modify its argument, there is no reason not to use a const reference.

Also this is a small thing, but I'd change the name of SumLength to AddLength as Sum to me suggests that it operates on multiple strings.

Other than that your code looks perfectly fine and straight forward.

Context

StackExchange Code Review Q#1198, answer score: 9

Revisions (0)

No revisions yet.