From 338da253e40bdb65b1f8dc753227e408472163a3 Mon Sep 17 00:00:00 2001 From: Christian Herdtweck Date: Fri, 17 Feb 2017 18:09:40 +0100 Subject: [PATCH] Create vector-result-version of split_string with unit test [Note from Tom during review: Can still be optimized later on when the API is in place] --- src/stringfunc.cpp | 21 +++++++++++++++++++++ src/stringfunc.hxx | 8 ++++++++ test/stringfunc.cpp | 11 +++++++++++ 3 files changed, 40 insertions(+), 0 deletions(-) diff --git a/src/stringfunc.cpp b/src/stringfunc.cpp index c50eb24..07f8113 100644 --- a/src/stringfunc.cpp +++ b/src/stringfunc.cpp @@ -380,6 +380,27 @@ void split_string( } // eo split_string(const std::string&,std::list< std::string >&,const std::string&,bool,const std::string&) +/** call split_string with list, converts result to vector; vector is clear()-ed first + * + * Note: Uses 3 O(n)-operations: list.size, vector.resize and std::swap_ranges; + * not sure whether there is a better way to do this + * */ +void split_string( + const std::string& str, + std::vector& result, + const std::string& delimiter, + bool omit_empty, + const std::string& trim_list +) +{ + std::list tmp; + split_string(str, tmp, delimiter, omit_empty, trim_list); + std::size_t size = tmp.size(); // this is O(n) + result.clear(); + result.resize(size); // also O(n) + std::swap_ranges(tmp.begin(), tmp.end(), result.begin()); // also O(n) +} + /** * splits a string by a given delimiter * @param str the string which should be splitted. diff --git a/src/stringfunc.hxx b/src/stringfunc.hxx index 67c38e7..0d9e363 100644 --- a/src/stringfunc.hxx +++ b/src/stringfunc.hxx @@ -114,6 +114,14 @@ void split_string( const std::string& trim_list= std::string() ); +void split_string( + const std::string& str, + std::vector< std::string >& result, + const std::string& delimiter= "\n", + bool omit_empty= false, + const std::string& trim_list= std::string() +); + std::list< std::string > split_string( const std::string& str, const std::string& delimiter = "\n", diff --git a/test/stringfunc.cpp b/test/stringfunc.cpp index ee18355..cb18ae9 100644 --- a/test/stringfunc.cpp +++ b/test/stringfunc.cpp @@ -598,6 +598,17 @@ BOOST_AUTO_TEST_CASE(SplitStringDelimiterOnly) } // eo SplitStringDelimiterOnly +BOOST_AUTO_TEST_CASE(SplitToVector) +{ + std::string line("0;1;2;3;4;5;6;7;8;9"); + std::vector result; + split_string(line, result, ";"); + BOOST_REQUIRE_EQUAL(result.size(), 10); + BOOST_CHECK_EQUAL(result[0], "0"); + BOOST_CHECK_EQUAL(result[4], "4"); + BOOST_CHECK_EQUAL(result[9], "9"); +} + BOOST_AUTO_TEST_CASE(JoinString1) { -- 1.7.1