一次递增所有数组元素1 [英] incrementing all array elements at a time by 1
问题描述
如何一次递增数组元素1 ...即
i有一个数组作为数组[1,2,3,4,5],是否有内置函数(或者在java或C)中,每次增加或减少
,变为数组[2,3,4,5,6]。
How to increment array elements at a time by 1...i.e
i have an array as array[1,2,3,4,5], is there any built in function(either in java or C) to increment or decrement
by 1 at a time which becomes as array[2,3,4,5,6].
推荐答案
没有这样的'内置'函数(至少在C
中,我相信Java
也没有这样的功能)可能是因为正如 ridoy 正确指出的那样,你可以自己轻松地实现它。
There is not such a 'built-in' function (at least inC
, I believeJava
has not such a function too) possibly because, as ridoy correctly pointed out, you may easily implement it yourself.
我不知道你为什么搜索内置函数来执行此操作,因为只有2行代码将获得所需的代码。看看它是如何完成的:
I don't know why you are searching for a built in function to do this as only 2 lines of code will get the desired code.Look how it could be done:
int[] myArray = {1,2,3,4,5};
int temp=0;
for(int i=0; i<myArray.length; i++)
{
temp = myArray[i]+1;
myArray[i] = temp;
}
//your array value was changed above,now see exactly it works or not!
for(int k=0; k < myArray.length; k++)
System.out.println(myArray[k]);
Output:
2,3,4,5,6
希望对您有所帮助。
干杯!
Shuvro
Hope that will help you.
Cheers!
Shuvro
在C ++中你可以使用类std :: valarray
。它类似于std :: vector
,但定义了许多单独修改每个元素的标准运算符。查看 http://www.cplusplus.com/reference/valarray/valarray/operators/ [ ^ ]作为参考;它还包括一些示例代码。
对于递增数组,你可以写e。 g。:
In C++ you can use the classstd::valarray
. It is similar tostd::vector
, but defines a number of standard operators that modify each element individually. check out http://www.cplusplus.com/reference/valarray/valarray/operators/[^] as a reference; it also includes some example code.
For incrementing an array you could write e. g.:
#include <valarray> // std::valarray
void foo ()
{
int myarray[]= {10,20,30,40};
std::valarray<int> bar (myarray, 4); // 10 20 30 40
bar += 1; // 11 21 31 41
}
PS:
如果在Windows中使用此类,则会发出警告:某些标准Windows头文件 #defines
宏 min()
和 max()
,这将会破坏函数 std :: valarray :: min()
和 std :: valarray :: max()
如果包括的valarray
。你可以用各种方式防止这种情况:
1.使用 #undef
来杀死这些定义
2.使用 #define NOMINMAX
在包含windows标题之前阻止他们的定义
3. #include
valarray
首先
(我讨厌 #define的原因中的一个<= code>!)
P.S.:
A word of warning if you use this class in Windows: some standard windows header file #defines
the macros min()
and max()
, which will nuke the functions std::valarray::min()
and std::valarray::max()
if included before you include valarray
. You can prevent this in various manners:
1. use #undef
to kill these definitions
2. use #define NOMINMAX
before including the windows headers to prevent their definition
3. #include
valarray
first
(Just one of the many reasons why I hate #define
!)
这篇关于一次递增所有数组元素1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!