打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
原来代码可以这么写 --记性不好的matthew

今天在google groups 的comp.lang.c++邮件列表里看到这么一段代码,真是有意思,我是第一次看到这种代码。

#include <iostream>

int main()
{
  int arr[3] = {1, 2, 3};

  for (int i = 0; i < 3; ++i)
    std::cout << i[arr] << " ";

  std::cout << std::endl;
 
  for (int j = 0; j < 3; ++j)
      std::cout << arr[j] << " ";

  std::cout << std::endl;

  return 0;
}

据说是利用了加法的交换性和传递性(commutativity and transitivity of addition)。

推导过程:
[quote]
.......

Using the transitivity of addition (meaning that A+B == B+A) we can
get some pretty ugly, but valid, syntax when indexing into arrays:

So arr[N] == *(arr + N) then we apply the transitivity rule on the
left hand giving *(N + arr) and then go back to the array-form gives
N[arr].

So given array arr then 2[arr] will give the third element in arr. And
then we replace the N with a variable and we get something like this:

int main()
{
  int arr[3] = {1, 2, 3};
  for (int i = 0; i < 3; ++i)
    std::cout << i[arr];
  return 0;
}
[/quote]

原文:
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/599be6c63ddaba57?hl=en

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
c++ vector用法(1)
Vector 容器
从快速排序来看迭代和递归的区别
C++this指针应用
九大排序算法的手写实现及时空复杂度分析 笔试面试必备
少写点if-else吧,它的效率有多低你知道吗?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服