boost::to_upper_copy 有兩個重載版本,第二種尤其值得注意,因為它的第二個參數是 range,用法與第一種差別不小。
template<typename OutputIteratorT, typename RangeT>
OutputIteratorT
to_upper_copy(OutputIteratorT Output, const RangeT & Input,
const std::locale & Loc = std::locale());
template<typename SequenceT>
SequenceT to_upper_copy(const SequenceT & Input,
const std::locale & Loc = std::locale());
// to_upper_copy 兩種重載函數
void test_string_upper()
{
std::string str1 = "Hello world!";
// 方法1
std::string str2 = boost::to_upper_copy(str1);
assert(str2 == "HELLO WORLD!");
// 方法2,第二個參數是 range,可以是如下幾種類型
// 1. make_pair(iterator, iterator)
// 2. std::string
// 3. 數組
std::string str3 = "str3 = ";
boost::to_upper_copy(std::back_inserter(str3), std::make_pair(str1.begin(), str1.end()));
assert(str3 == "str3 = HELLO WORLD!");
std::string str4 = "str4 = ";
boost::to_upper_copy(std::back_inserter(str4), "HELLO WORLD!");
assert(str4 == "str4 = HELLO WORLD!");
std::string str5 = "str5 = ";
boost::to_upper_copy(std::back_inserter(str5), boost::make_iterator_range(str1));
assert(str5 == "str5 = HELLO WORLD!");
std::string str6 = "str6 = ";
char* p = "HELLO WORLD!";
boost::to_upper_copy(std::back_inserter(str6), p);
assert(str6 == "str6 = HELLO WORLD!");
}
兩者的區別在於返回方式:第一個重載把結果寫入 Output 迭代器並返回該迭代器,源與目標可以是不同容器,因此能實現「轉大寫並追加到另一個字符串」;第二個重載直接返回一個新序列,最常用。
第二種之所以能接受 make_pair 得到的迭代器對、字符串字面量、std::string 甚至 boost::make_iterator_range,靠的是 Boost.Range 對「range」概念的統一抽象——凡是能取到 begin/end 的東西都算 range。字面量與 char* 之所以可行,是因為 Boost 對 C 字符串做了特殊處理,會用 strlen 推導出末尾。
還有一點實用細節:兩個版本都帶一個默認參數 std::locale,因此可以指定區域設置來決定哪些字符算大寫,處理非 ASCII 字符時這比 std::toupper 更可靠。