Flexible C++

C++是一门非常灵活的语言,只要充分发挥你的想象, 再普通的东西都能玩出新花样

1、1~1000求和
循环?递归?再简单不过的题目了。但是如果不允许你用判断语句呢?
如果你熟悉switch的内部实现,那么你很容易想到使用函数指针数组。

#include <cstdio>

typedef int (*fun)(int);

int f1(int i) {return 0;}
int f2(int i) {fun f[2]={f1,f2}; return i+f[!!i](i-1);}
int main()
{
    printf("%d/n",f2(1000));
}

2、输出1,2,...,100,99,...,2,1
如果同样不让你用判断语句呢?你仍然可以使用函数指针数组:

#include <cstdio>

typedef void (*fun)(int i,int n);

void f1(int i,int n);
void f2(int i,int n);
void f3(int i,int n);

void f1(int i,int n)
{
    fun f[2]={f1,f2};

    printf("%d/n",i);
    f[i+1==n](i+1,n);
}
void f2(int i,int n)
{
    fun f[2]={f2,f3};

    printf("%d/n",i);
    f[i==1](i-1,n);
}
void f3(int i,int n) {}

int main()
{
    f1(1,100);
}

不过我们有更简洁的方法。
短路算法和逗号表达式粉墨登场了,一行搞定~

#include <cstdio>

void f(int i,int n)
{
    printf("%d/n",i),(i<n)&&(f(i+1,n),printf("%d/n",i));
}

int main()
{
    f(1,100);
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ templates are a powerful feature of the C++ programming language that allow for generic programming. Templates allow developers to write code that works with a wide range of data types, without having to write separate code for each individual type. Templates are defined using the keyword "template", followed by a list of template parameters within angle brackets. These parameters can be data types, values, or other templates. For example, a simple template function that adds two numbers could be written as: ``` template <typename T> T add(T a, T b) { return a + b; } ``` In this example, the template parameter "T" is used to represent the data type of the variables a and b. The function can be called with any data type that supports the "+" operator, such as int, float, or even custom classes that define their own operator overloads. Templates can also be used to define classes, which can be useful for creating generic data structures or algorithms. For example, a template class for a dynamic array could be written as: ``` template <typename T> class DynamicArray { private: T* data; int size; public: // constructor, destructor, and other methods // ... }; ``` In this example, the template parameter "T" is used to represent the data type stored in the dynamic array. The class can be instantiated with any data type, and the data array will be allocated accordingly. Overall, templates are a powerful tool for creating flexible and reusable code in C++. However, they can also be complex and difficult to understand, so they should be used judiciously and with care.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值