|
-
July 23rd, 2004, 01:08 AM
#1
query related to array and pointer
is this implementation correct
Following function Rotate is for rotating datavalues in the array to the value as mentioned in shift.
shift can be + ve and -ve
+ve shift means element at 0 moves to 'shift' position. For eg. if shift is 45 then element at 0 moves to 45 th position and hence complete rearragned like this
Code:
void Rotate(float *arr, int shift)
{
float tmp[4096];
// If shift is more than the size, restrict it to the size
if(shift > 4095)
shift = 4095;
for(int i=shift; i<4096; i++)
{
tmp[i] = arr[i-shift];
}
for(i=0; i<shift; i++) // if (shift > 0) clear wwrot shift
{
tmp[i] = 0;
}
for(i=0; i<4096; i++)
{
arr[i] = tmp[i];
}
}
-
July 23rd, 2004, 04:02 AM
#2
Don't use the temporary array. It limits you with a constant size (in your case 4096), and since you modify the original array it gives no advantage.
what happens when shift is negative?
Code:
...
for(int i=shift; i<4096; i++)
{
tmp[i]=... ==> underflow problem
**** **** **** **** **/**
-
July 23rd, 2004, 07:43 AM
#3
Maybe memcpy could accelerate your function or you could use the stl-function rotate...
Code:
void Roatate( std::vector<float> &v, int shift )
{
typedef std::vector<float>::iterator Iter;
Iter begin, end, middel;
begin = v.begin();
end = v.end();
if( abs(shift) >= v.size() )
shift = v.size()-1;
if( shift<0 )
middel = begin+shift;
else
middle = end-shift;
rotate( begin, middel, end );
}
I didnt test this code. Tell me if it works or not!
Hope i could help you...
cu
-
July 23rd, 2004, 07:52 AM
#4
But i think the best way to solve this problem is to write a class that overwrite the operator[]. Then you have only to handle with three pointers. the beginning of the array, the end of the array and the position where the virtual beginning of you array is:
pseudocode
Code:
class ShiftArray
{
public:
operator<<(); //shift left. Only set beginning pointer (vbegin) of array
operator>>(); //shift right. Only set begining pointer (vbegin) of array
refernece operator[](int);
private:
arrayPointer *begin, *end, *vbegin;
};
Then, for example ShiftArray: perator[](0) returns you *vbegin;
cu
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|