小编Dal*_*ton的帖子

由于对模板化类型的通用(前向)引用而无法实例化函数模板

通用参考(即"前向参考",c++标准名称)和完善的转发c++11,c++14具有许多重要优势; 看到这里,在这里.

在上面引用的Scott Meyers的文章(链接)中,根据经验表明:

如果变量或参数声明为某个推导类型 T的类型为T &&,则该变量或参数是通用引用.

例1

实际上,使用clang ++我们看到以下代码片段将成功编译-std=c++14:

#include <utility>

template <typename T>
decltype(auto) f(T && t)
{
    return std::forward<T>(t);
}

int        x1 = 1;
int const  x2 = 1;
int&       x3 = x1;
int const& x4 = x2;

// all calls to `f` result in a successful
// binding of T&& to the required types
auto r1 = f …
Run Code Online (Sandbox Code Playgroud)

c++ templates perfect-forwarding c++11 c++14

11
推荐指数
1
解决办法
1053
查看次数

C使用与index对应的值初始化(非常)大整数数组

Edit3:通过将数组的初始化限制为仅奇数来优化.谢谢@Ronnie!

编辑2:谢谢大家,似乎没有什么可以做的了.

编辑:我知道Python和Haskell是用其他语言实现的,并且或多或少地执行我所遵循的相同操作,并且编译的C代码将在任何一天击败它们.我只是想知道标准C(或任何库)是否具有内置函数来更快地执行此操作.

我正在使用Eratosthenes的算法在C中实现一个主筛,并且需要初始化从0到n的任意大小n的整数数组.我知道在Python中你可以这样做:

integer_array = range(n)
Run Code Online (Sandbox Code Playgroud)

就是这样.或者在Haskell:

integer_array = [1..n]
Run Code Online (Sandbox Code Playgroud)

但是,我似乎无法找到在C中实现的类似方法.我已经提出的解决方案初始化数组然后迭代它,在该点将每个值分配给索引,但它感觉非常低效.

int init_array()
{
    /* 
    * assigning upper_limit manually in function for now, will expand to take value for
    * upper_limit from the command line later.
    */
    int upper_limit = 100000000;
    int size = floor(upper_limit / 2) + 1;

    int *int_array = malloc(sizeof(int) * size);
    // debug macro, basically replaces assert(), disregard.    
    check(int_array != NULL, "Memory allocation error");

    int_array[0] = 0;
    int_array[1] = 2;

    int …
Run Code Online (Sandbox Code Playgroud)

c arrays

5
推荐指数
2
解决办法
1218
查看次数

标签 统计

arrays ×1

c ×1

c++ ×1

c++11 ×1

c++14 ×1

perfect-forwarding ×1

templates ×1