diff options
| author | 冯昶 <fengchang@novel-supertv.com> | 2024-01-29 18:09:34 +0800 |
|---|---|---|
| committer | 冯昶 <fengchang@novel-supertv.com> | 2024-01-29 18:09:34 +0800 |
| commit | 4fcb283e68607d4c866ede316ee75b5352106ec7 (patch) | |
| tree | ac11d0c80ba3e9134319176a1278132208202a5e /challenge-253/witawayar/cpp/ch-1.cpp | |
| parent | b272c7f737b5969c4ce12783dc47a8d7a6af6574 (diff) | |
| parent | 4099837cf3689e1d78a66905fde9c5a45ff95940 (diff) | |
| download | perlweeklychallenge-club-4fcb283e68607d4c866ede316ee75b5352106ec7.tar.gz perlweeklychallenge-club-4fcb283e68607d4c866ede316ee75b5352106ec7.tar.bz2 perlweeklychallenge-club-4fcb283e68607d4c866ede316ee75b5352106ec7.zip | |
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'challenge-253/witawayar/cpp/ch-1.cpp')
| -rw-r--r-- | challenge-253/witawayar/cpp/ch-1.cpp | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/challenge-253/witawayar/cpp/ch-1.cpp b/challenge-253/witawayar/cpp/ch-1.cpp new file mode 100644 index 0000000000..9f0c138e5e --- /dev/null +++ b/challenge-253/witawayar/cpp/ch-1.cpp @@ -0,0 +1,46 @@ +// g++ -Wall -Wextra -Wpedantic -std=c++17 cpp/ch-1.cpp +#include <algorithm> // remove_if +#include <iostream> // cout +#include <sstream> // stringstream +#include <vector> + +std::vector<std::string> fun(std::vector<std::string> const& words, std::string separator) { + std::vector<std::string> parts; + std::size_t sep_size = separator.size(); + + for (auto& sub_word : words) { + std::size_t start = 0; + for (size_t found = sub_word.find(separator); + found != std::string::npos; + found = sub_word.find(separator, start)) { + parts.emplace_back(sub_word.begin() + start, sub_word.begin() + found); + start = found + sep_size; + } + if (start != sub_word.size()) + parts.emplace_back(sub_word.begin() + start, sub_word.end()); + } + parts.erase(std::remove_if(parts.begin(), parts.end(), [](std::string const& str) { + return str.find_first_not_of(' ') == std::string::npos; }), parts.end()); + + return parts; +} + +int main(void) { + // Tests + std::vector<std::pair<std::pair<std::vector<std::string>, std::string>, std::vector<std::string>>> tests = { + {{{"one.two.three", "four.five", "six"}, "."}, {"one", "two", "three", "four", "five", "six"}}, + {{{"$perl$$", "$$raku$"}, "$"}, {"perl", "raku"}} + }; + + for (const auto& [input, expected_output] : tests) { + auto [words, separator] = input; + auto got = fun(words, separator); + if (got != expected_output) { + std::stringstream error_msg; + error_msg << "Failed at " << separator; + throw std::runtime_error(error_msg.str()); + } + } + + std::cout << "done-testing, success\n"; +} |
