#include "./example.hpp" #include #include #include #include #include static void introduction() { //[algorithm_introduction /*`For example, the following snippet converts an array of integers from their textual hexadecimal representation and assigns INT_MAX to those which fail to convert: */ boost::array strings = {{ " 5", "0XF", "not an int" }}; std::vector integers; boost::cnv::cstringstream cnv; // stringstream-based char converter cnv(std::hex)(std::skipws); std::transform( strings.begin(), strings.end(), std::back_inserter(integers), boost::convert(cnv).value_or(INT_MAX)); BOOST_TEST(integers.size() == 3); BOOST_TEST(integers[0] == 5); BOOST_TEST(integers[1] == 15); BOOST_TEST(integers[2] == INT_MAX); // Failed conversion //] } static void example1() { //[algorithm_example1 /*`The following code demonstrates a failed attempt to convert a few strings with `boost::lexical_cast`: */ boost::array strs = {{ " 5", "0XF", "not an int" }}; std::vector ints; try { std::transform( strs.begin(), strs.end(), std::back_inserter(ints), boost::bind(boost::lexical_cast, _1)); BOOST_TEST(!"We should not be here"); } catch (std::exception&) { // No strings converted. BOOST_TEST(ints.size() == 0); } //] } static void example2() { //[algorithm_example2 /*`The first take by ['Boost.Convert] is more successful (it knows how to handle the hexadecimal format and to skip white spaces) but still not quite satisfactory (your mileage may vary) as conversion is interrupted when ['Boost.Convert] comes across an invalid input: */ boost::array strs = {{ " 5", "0XF", "not an int" }}; std::vector ints; boost::cnv::cstringstream cnv; try { std::transform( strs.begin(), strs.end(), std::back_inserter(ints), boost::convert(cnv(std::hex)(std::skipws))); BOOST_TEST(!"We should not be here"); } catch (std::exception&) { // Only the first two strings converted. Failed to convert the last one. BOOST_TEST(ints.size() == 2); BOOST_TEST(ints[0] == 5); BOOST_TEST(ints[1] == 15); } //] } static void example3() { boost::array strs = {{ " 5", "0XF", "not an int" }}; std::vector ints; boost::cnv::cstringstream cnv; //[algorithm_example3 /*`And at last a fully working version (with a conversion-failure fallback value provided): */ std::transform( strs.begin(), strs.end(), std::back_inserter(ints), boost::convert(cnv(std::hex)).value_or(-1)); BOOST_TEST(ints.size() == 3); BOOST_TEST(ints[0] == 5); BOOST_TEST(ints[1] == 15); BOOST_TEST(ints[2] == -1); // Failed conversion //] } void example::algorithms() { introduction(); example1(); example2(); example3(); }