Foreach
foreach是新引入的一种for循环形式,常见语法如下:
decl是coll集合中每个元素的声明
for(decl: coll)
{
//run
}
for的转换
对于集合种提供成员函数如begin(),或者end()等产生的foreach如下
template <typename T>
void printf_elem(const std::initializer_list<T> team)
{
for (const auto & elem : team)
{
cout << elem << endl;
}
}
int main()
{
printf_elem({ 1,2,3,4,5,6 });
template <typename T>
void printf_elem(const std::initializer_list<T> team)
{
for (auto t=team.begin();t!=team.end();t++)
{
const auto &elem = *t;
cout << elem << endl;
}
}
int main()
{
printf_elem({ 1,2,3,4,5,6 });
而对于没有begin()等成员函数的集合则采用全局性的begin()和end()来接受实参
int t[] = { 1,2,3,4,5,6 };
for (const auto & elem : team)
{
cout << elem << endl;
}
int main()
{
int t[] = { 1,2,3,4,5,6 };
for (auto temp=begin(t);temp!=end(t);temp++)
{
const auto &elem = *temp;
cout << elem<< endl;
}
}
String Literal
c++11提供新式的字符串字面常量,可以节约许多修饰符的符号
Raw string 以R“(…)”来表示一个字符串。如下两者相等:
"ab\\\\n"
R"(ab\\n)"
如果要在Raw string 中写入"( 或者 ) “等可以使用定义符
表示为R"test( …)test” ,其中的test为字符序列 最多16个字符不可含反斜线 空格 小括号。
如下 两者相等
R"test( "(123\t123 )test"
\"(123\\t123
又如下 两者相等
R"test(a\
b\nc()"
)test"
"a\\\n b\\nc()\"\n
编码的String Literal
String Literal可以使用编码前缀,你可以定义一个特殊的字符编码
u8 定义 UTF-8的字符
u定义一个char_16_t的字符
U定义一个char_32_t的字符
L定义一个wchar_t的字符
cout <<LR"(你好)" << endl;
cout <<u8R"(你好)" << endl;