如何初始化数组相同数量的C中的所有元素++ [英] How to initialize all elements in an array to the same number in C++

查看:161
本文介绍了如何初始化数组相同数量的C中的所有元素++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想初始化的一切设定在-1 int数组。

I'm trying to initialize an int array with everything set at -1.

我尝试以下,但它不工作。它仅在-1设置第一值

I tried the following, but it doesn't work. It only sets the first value at -1.

int directory[100] = {-1};

为什么它不工作的权利?

Why doesn't it work right?

推荐答案

我在所有的答案提示惊讶矢量。他们甚至不一样的东西!

I'm surprised at all the answers suggesting vector. They aren't even the same thing!

使用 的std ::填写 ,从<&算法GT;

int directory[100];
std::fill(directory, directory + 100, -1);


不关心直接的问题,但是当涉及到​​阵列你可能要一个很好的辅助函数:


Not concerned with the question directly, but you might want a nice helper function when it comes to arrays:

template <typename T, size_t N>
T* end(T (&pX)[N])
{
    return pX + N;
}

捐赠:

int directory[100];
std::fill(directory, end(directory), -1);

所以,你不需要列出的两倍。

So you don't need to list the size twice.

这篇关于如何初始化数组相同数量的C中的所有元素++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆