I have a vector int a[100], initialised with values such as 9726745. How do I set them all to a specific value x without a for statement?
Printable View
I have a vector int a[100], initialised with values such as 9726745. How do I set them all to a specific value x without a for statement?
I don't think you can do it without looping (at least indirectly).
>without a for statement?
With a while statement :D
You can use memset() to do this.
Edited: Irrelevant.
Never mind the fact that there are no vectors in C.Quote:
Originally posted by XSquared
It's not safe to use memset( ) with a vector.
Quzah.
Are we talking about an array here or a vector class? For an array, my example will most certainly work. For a vector class it won't, but this is the C programming board not C++.
Heh. Oops.
As soon as I saw vector my mind snapped into C++ mode.
Proper handling of memset is save with an array.
It is always save to set all bits to zero in an array of char (signed or unsigned),but thats all.C allows every single
data type except {signed,unsigned} char to have padding bits, that are not part
of the representation of the value. It is possible that improper
combinations of these padding bits can generate what is called a trap
representation.
So,for example memseting an array of ints to zero is not save (nonportable).
[OT]
The memory of std::vector is continous,memseting a std::vector of {unsigned,signed} chars is save too.
[/OT]
Please, just take the easy obvious way:
Code:int a[100];
for (int i=0;i<100;i++)
{
a[i]=0;
}
One way to assign to an array without a loop is to wrap the array in a structure.Code:#include <stdio.h>
struct sType
{
int a[10];
};
const struct sType Default = {{56,7,8,1,27,13,54,82,23,16}};
void show(const int *array, size_t size)
{
size_t i;
for ( i = 0; i < size; ++i )
{
printf("%2d%c", *array++, i % 10 == 9 ? '\n' : ',');
}
}
int main(void)
{
struct sType object = {{83,6,71/*remaining elements are 0*/}};
fputs("Before: ", stdout);
show(object.a, sizeof(object.a)/sizeof(*object.a));
object = Default;
fputs("After: ", stdout);
show(object.a, sizeof(object.a)/sizeof(*object.a));
return 0;
}
/* my output
Before: 83, 6,71, 0, 0, 0, 0, 0, 0, 0
After: 56, 7, 8, 1,27,13,54,82,23,16
*/
Here's an obvious answer: at the time of declaration:
int foo[5] = { 1, 1, 1, 1, 1 };
Of course, you could always use recursion:
There's a few missed ways. That'll suffice for now.Code:void fill( int array[], size_t size, int value )
{
if( size > -1 )
{
fill( array, size-1, value );
array[size] = value;
}
}
Quzah.