I would like to do the following but Xcode can't make sense of duck[x]:
NSArray *duck1;
NSArray *duck2;
NSArray *duck3;
for ( int x=0; x < count; x++ ) {
duck[x]= #[[otherArrayOne objectAtIndex:x], [otherArrayTwo objectAtIndex:x], [otherArrayThree objectAtIndex:x], ];
}
but xCode doesn't like: 'duck[x]'
Xcode is right in prompting compile time error. Variable 'duck' is un-declared in your code.
You just have to declare 'duck' variable and initialize it. Add following lines after NSArray *duck3; variable declarations.
NSArray *duck = #[duck1,duck2,duck3];
int count = [duck count];
Related
I was just curious to know if there is way to create a new variable with a new name every time a loop is executed.
For example:
#include <iostream>
int main()
{
for (int x = 1 ; x<=5 ; x++)
int a_x;
return 0;
}
5 new variables should be created with names a_1, a_2, ..., a_5
The above code just shows what I am looking for and is not the answer.
Is this possible without using arrays?
No, there is no way to do what you've outlined (directly). Here are several possible alternatives:
First off, if you do not need the "variables" to be accessible outside the loop, just use a normal local variable:
for (int x = 1; x <= 5; ++x) {
int a = whatever; // This will be freshly redeclared & reinitialised in each iteration
}
If the bounds of the iteration are known at compile time, you can use an array:
std::array<int, 5> a;
for (int x = 0; x < a.size(); ++x) {
a[x];
}
If the bounds are only known at runtime, use a dynamic array:
std::vector<int> a(the_runtime_size);
for (int x = 0; x < a.size(); ++x) {
a[x];
}
If you really need individual variables for some reason (and you know the number at compile time), you could resort to preprocessor tricks with Boost.Preprocessor. But that is far above beginner level:
#include <boost/preprocessor>
#define DECLARE_MY_VARIABLE(z, idx, name) \
int BOOST_PP_CAT(name, BOOST_PP_CAT(_, idx));
BOOST_PP_REPEAT(5, DECLARE_MY_VARIABLE, a)
The code above will expand to:
int a_0; int a_1; int a_2; int a_3; int a_4;
You could of course take this several steps further, to have each of the variables of a different type, or name them by names instead of by indices. It will just require more macro magic.
Disclaimer: Do NOT use this approach unless you very clearly know you need it. Even then, reconsider twice before you actually do that. And if you still do, document it heavily. Stuff like this should generally be hidden deep inside a library under a nice & clean user-friendly interface.
No you can't do that in C++.
The best thing to do in this case would be to create an array of ints and use the for loop to populate them.
int a_x[5];
for (int x = 1 ; x<=5 ; x++)
a_x[x - 1] = /*ToDo - something*/
Note that
arrays are zero-based: can you see how I've used x - 1. The normal thing to do would be to rebase x in the for loop though: for (int x = 0 ; x < 5; ...
arrays are not initialised. You must populate the contents.
While many will assume that this is impossible, it can be achieved with the preprocessor. It is necessary that the loop count is known at compile time. Here I use the Boost Preprocessor Library. The example for PP_REPEAT does almost exactly what you want.
#include <boost/preprocessor/repetition/repeat.hpp>
#define DECL(z, n, text) text ## n = n;
int main()
{
BOOST_PP_REPEAT(5, DECL, int a_) // expands to int a_0 = 0; int a_1 = 1; ...
return 0;
}
Please remember: this is certainly not what you want. You probably want to use an array. Do only use this if you are absolutely certain that you need it.
I wanted to write a program displaying all CPU options on a current CPU.
Individual calls like this work:
if (__builtin_cpu_is("intel"))
Instead I would prefer to declare an array:
const char* cpuType[] = {
"intel", "atom", "core2", "corei7", "nehalem",
"westmere", "sandybridge", "amd", "amdfam10h", "barcelona",
"shanghai", "istanbul", "btver1", "amdfam15h",
"bdver1", "bdver2", "bdver3", "bdver4", "btver2"
}
and in a loop check the same thing:
for (int i = 0; i < sizeof(cputype)/sizeof(char*); i++)
if (__builtin_cpu_is(cpuType[i])
gcc refuses, saying it has to be a constant string.
Is there any way to make this work aside from writing the code over and over?
I am using a library that returns a a series of ints using a parameter that looks like:
int ** outList
What is the best way to take that and wrap it in a bunch of NSNumber objects (and perhaps an NSArray to hold them)?
There is no shortcut, that I know of. You can write something like this:
int **outList = ...
int count = ...
NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:count];
for (int idx = 0; idx < count; idx++)
[result addObject:#(outList[idx])];
Hope it helps!
As above, I'm trying to create and then fill an array of structures with some starting data to then write to/read from.
I'm still writing the cache simulator as per my previous question:
Any way to get rid of the null character at the end of an istream get?
Here's how I'm making the array:
struct cacheline
{
string data;
string tag;
bool valid;
bool dirty;
};
cacheline **AllocateDynamicArray( int nRows, int nCols)
{
cacheline **dynamicArray;
dynamicArray = new cacheline*[nRows];
for( int i = 0 ; i < nRows ; i++ )
dynamicArray[i] = new cacheline [nCols];
return dynamicArray;
}
I'm calling this from main:
cacheline **cache = AllocateDynamicArray(nooflines,noofways);
It seems to create the array ok, but when I try to fill it I get memory errors, here's how I'm trying to do it:
int fillcache(cacheline **cache, int cachesize, int cachelinelength, int ways)
{
for (int j = 0; j < ways; j++)
{
for (int i = 0; i < cachesize/(cachelinelength*4); i++)
{
cache[i][ways].data = "EMPTY";
cache[i][ways].tag = "";
cache[i][ways].valid = 0;
cache[i][ways].dirty = 0;
}
}
return(1);
}
Calling it with:
fillcache(cache, cachesize, cachelinelength, noofways);
Now, this is the first time I've really tried to use dynamic arrays, so it's entirely possible I'm doing that completely wrong, let alone when trying to make it 2d, any ideas would be greatly appreciated :)
Also, is there an easier way to do write to/read from the array? At the moment (I think) I'm having to pass lots of variables to and from functions, including the array (or a pointer to the array?) each time which doesn't seem efficient?
Something else I'm unsure of, when I pass the array (pointer?) and edit the array, when I go back out of the function, will the array still be edited?
Thanks
Edit:
Just noticed a monumentally stupid error, it should ofcourse be:
cache[i][j].data = "EMPTY";
You should find your happiness. You just need the time to check it out (:
The way to happiness
I am using Qt on Ubuntu. When I debug I only see the very first value of the array in Locals and Watchers. How can I view all the array contents?
struct node
{
int *keys;
void **pointers;
int num_keys;
struct node *parent;
int is_leaf;
struct node *nextLevelNode;
};
It shows only the first key value in the debugging window.
In Expression evaluator,
Try (int[10])(*myArray) instead of (int[10])myArray
Or, *myArray#10 instead of myArray#10
It shows only the first key value,in the debugging window
I presume you're referring to the pointer keys, declared with int *keys;
The debugger doesn't know that this is an array: all it knows is that this is a pointer to an int. So it can't know how many values you want it to display.
What I've found, using the Qt Creator 2.1.0 debugger on Ubuntu, is that the following code allows me to see all 5 values:
int array1[5];
array1[0] = 2;
array1[1] = 4;
array1[2] = 6;
array1[3] = 8;
array1[4] = 10;
Whereas with this code, the debugger only shows the first value, exactly as you describe.
int* array2 = new int[5];
array2[0] = 20;
array2[1] = 21;
array2[2] = 22;
array2[3] = 23;
array2[4] = 24;
Aside: of course, the above code would be followed by this, to avoid leaking memory:
delete[] array2;
Later: This Qt Developer Network Forum Post says that you can tell the debugger to display a pointer as an array:
In Locals and Watchers, context menu of your pointer’s entry, select “Watch Expression”. This creates a new watched expression below.
There, double click on the entry in the “Names” column, and add “#10” to display 10 entries.
This sounds like it should get you going.
Just right-click on your variable, and choose Change Value Display Format and check Array of 100 items.
In Qt for mac what worked for me was:
Add an expression evaluator for the desired variable (right click the variable on the debugger window then "Add expression evaluator for "var name here""
The array variable appears initially as a single value. Just change "var" to "var[start...end] and the array values appear.
Two dimensional arrays sometimes cannot be displayed that way. There is a work-around. First, declare a two-dimensional array as a one-dimensional array like this:
int width = 3;
int height = 4;
int* array2D = new int [width*height];
int x,y;
for(x=width-1;x>-1;x--)
for(y=height-1;y>-1;y--)
array2D[x*height + y] = -1; // mark a breakpoint here!
// add to expression evaluator: (int[3][4]) *array2D
delete [] array2D;
Then add (int[3][4]) *array2D to the expression evaluator. Unfortunately you have to index the array your self, but you can write a special-purpose inline function or use another encapsulation method to make it slightly cleaner.