新特性(4)---Foreach,String Literal

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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工农村贴膜小哥

我倒是要看看是那个憨憨在给我打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值