string_ref
boost.string_ref是一種輕量級的字符串,它只持有字符串的引用,沒有內存拷貝成本,所以運行效率很高。
string_ref庫定義了basic_string_ref,接口與std::string很相似,以下爲類摘要:
- 它不拷貝字符串,所以就不分配內存,只用兩個成員變量ptr_和len_標記字符串都起始位置和長度,這樣就實現了字符串的表示。
- basic_string_ref是一個字符串的“常量視圖”,大部分成員函數都是const修飾的,我們只能像const std::string& 那樣去觀察字符串而無法修改字符串。
與std::basic_string類似,basic_string_ref也定義了幾個typedef方便使用:
使用:
#include <iostream>
#include <boost/utility/string_ref.hpp>
using namespace boost;
int main()
{
const char* ch = "Apple iPhone iPad";
//創建字符串引用
string_ref str(ch);
//獲取長度
std::cout << str.size();
//遍歷
for (auto& x : str)
{
std::cout << x;
}
std::cout << std::endl;
//類似容器的操作
std::cout << str.front();
//查找
std::cout << str.find('i');
//獲取子串,但是仍然是引用
std::cout << str.substr(6, 6);
//轉換爲標準string
std::string s = str.to_string();
//刪除前6個字符
str.remove_prefix(6);
//刪除後6個字符
str.remove_suffix(6);
//清空
str.clear();
getchar();
return 0;
}