2
0
mirror of https://github.com/boostorg/convert.git synced 2026-02-17 13:42:18 +00:00
Files
convert/doc/06_algorithms.qbk
2014-02-17 21:34:26 +11:00

68 lines
2.1 KiB
Plaintext

[section:convert_algorithms Boost.Convert with Standard Algorithms]
The following code demonstrates a failed attempt to convert a few strings with ['boost::lexical_cast]:
array<char const*, 5> strings = {{ "0XF", "0X10", "0X11", "0X12", "not int" }};
std::vector<int> integers;
try
{
std::transform(
strings.begin(),
strings.end(),
std::back_inserter(integers),
boost::bind(boost::lexical_cast<int, std::string>, _1));
BOOST_ASSERT(!"We should not be here");
}
catch (std::exception&)
{
// No strings converted.
}
The first take by ['boost::convert] is more successful but still not quite satisfactory (your mileage may vary) as conversion is interrupted when ['boost::convert] comes across an invalid input:
boost::array<char const*, 5> strings = {{ "0XF", "0X10", "0X11", "0X12", "not int" }};
std::vector<int> integers;
boost::cstringstream_converter cnv; // stringstream-based char converter
try
{
std::transform(
strings.begin(),
strings.end(),
std::back_inserter(integers),
convert<int>::from<string>(cnv(std::hex)));
BOOST_ASSERT(!"We should not be here");
}
catch (std::exception&)
{
// Only the first four strings converted. Failed to convert the last one.
BOOST_ASSERT(integers[0] == 15);
BOOST_ASSERT(integers[1] == 16);
BOOST_ASSERT(integers[2] == 17);
BOOST_ASSERT(integers[3] == 18);
}
And at last a fully working version (with a conversion-failure fallback value provided):
boost::array<char const*, 5> strings = {{ "0XF", "0X10", "0X11", "0X12", "not int" }};
std::vector<int> integers;
boost::cstringstream_converter cnv; // stringstream-based char converter
std::transform(
strings.begin(),
strings.end(),
std::back_inserter(integers),
convert<int>::from<string>(ccnv(std::hex)).value_or(-1));
BOOST_ASSERT(integers[0] == 15);
BOOST_ASSERT(integers[1] == 16);
BOOST_ASSERT(integers[2] == 17);
BOOST_ASSERT(integers[3] == 18);
BOOST_ASSERT(integers[4] == -1); // Failed conversion
[endsect]