Use stl algorithms instead of nested for loops

This commit is contained in:
Stephan van Veen 2019-05-11 12:24:01 +02:00
parent a364f3f1e7
commit 7c938b1f2b

View File

@ -40,6 +40,7 @@ SOFTWARE.
#include <algorithm> #include <algorithm>
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
#include <numeric>
namespace argparse { namespace argparse {
@ -635,19 +636,17 @@ class ArgumentParser {
// Used by print_help. // Used by print_help.
size_t get_length_of_longest_argument(const std::vector<std::shared_ptr<Argument>>& aArguments) { size_t get_length_of_longest_argument(const std::vector<std::shared_ptr<Argument>>& aArguments) {
size_t tResult = 0; if (aArguments.empty())
for (const auto& argument : aArguments) { return 0;
size_t tCurrentArgumentLength = 0; std::vector<size_t> argumentLengths(aArguments.size());
auto tNames = argument->mNames; std::transform(std::begin(aArguments), std::end(aArguments), std::begin(argumentLengths), [](const auto& arg) {
for (size_t j = 0; j < tNames.size() - 1; j++) { const auto& names = arg->mNames;
auto tNameLength = tNames[j].length(); auto maxLength = std::accumulate(std::begin(names), std::end(names), 0, [](const auto& sum, const auto& s) {
tCurrentArgumentLength += tNameLength + 2; // +2 for ", " return sum + s.size() + 2; // +2 for ", "
} });
tCurrentArgumentLength += tNames[tNames.size() - 1].length(); return maxLength - 2; // -2 since the last one doesn't need ", "
if (tCurrentArgumentLength > tResult) });
tResult = tCurrentArgumentLength; return *std::max_element(std::begin(argumentLengths), std::end(argumentLengths));
}
return tResult;
} }
// Used by print_help. // Used by print_help.
@ -670,7 +669,7 @@ class ArgumentParser {
try { \ try { \
parser.parse_args(argc, argv); \ parser.parse_args(argc, argv); \
} catch (const std::runtime_error& err) { \ } catch (const std::runtime_error& err) { \
std::cerr << err.what() << std::endl; \ std::cout << err.what() << std::endl; \
parser.print_help(); \ parser.print_help(); \
exit(0); \ exit(0); \
} }