1

I was wondering if there is an easy way to set more than one element of an array in a single line of code. For example, instead of:

int Array[10];
Array[4] = 100;
Array[7] = 100;

Is there some way to do something like the following?

int Array[10];
Array[4 & 7] = 100;

I know the above code doesn't work, but I can't really think of any other way to display my question. Anyhow, thanks in advance to anyone who would like to share their opinion :)

3
  • Valid language semantics aren't opinions, unless you're on the language committee. Commented Apr 25, 2012 at 4:27
  • 2
    Array[4]= Array[7] = 100; this is single line :) Commented Apr 25, 2012 at 4:31
  • You can also create a terse pointer or reference in local scope { int* a = Array; a[4] = a[7] = 100; }. Commented Apr 25, 2012 at 5:06

4 Answers 4

3
int array[10];
array[4] = array[7] = 100;
array[4] = 100, array[7] = 100;
4[array] = 7[array] = 100;

EDIT:

You may want to use loops for a somewhat dynamic setting of elements

int i, array[10], array_element[3] = { 3, 5, 6 };
for (i = 0; array_element[i] && array[array_element[i]]; i++) array[array_element[i]] = 100;

Another option is to define a function if by 'minimal' code you mean abstraction

overlord::set(array, 100, "3, 5, 6");
overlord::set(array, 100, "{ 3, 5, 6 }");
overlord::set(array, "3: 200, 5: 400, 6: 500");

Either way you won't find "DYNAMIC" language features in C++ or C. You'll have to implement an abstraction over basic existing functionality to be able to get that silly dynamic typing.

Sign up to request clarification or add additional context in comments.

Comments

0

You could possibly do it this way

 int Array[10];
 Array[4] = Array[7] = 100;

Comments

0

If you are trying to set a range of elements you can use a for loop

int array[10];
for(int i=0; i<10; i++) {
    array[i] = 100;
}

You can also do it for only certain numbers by using this trick

int nums[2] = { 4,7 }; //Positions you wish to set
for(int i=0; i<2; i++) {
    array[nums[i]] = 100;  //nums[0] = 4, array[4] 
                           //nums[1] = 7, array[7]
}

1 Comment

If you are trying to set a range of elements, you can use std::fill.
0

You have this perfectly readable code:

int Array[10];
Array[4] = 100;
Array[7] = 100;

And you want to "set more than one element of an array in a single line of code." Okay:

int Array[10];
Array[4] = 100; Array[7] = 100;

But why would you? Is there a newline shortage that I haven't heard about?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.