1
SomeClass* stuff;
int N = 10;
stuff = new SomeClass[N];

Someclass* objectPtrDelete = null;

int i = 0;
for(Someclass* pointer = begin(); pointer != end(); pointer++)
{
    if(pointer->getSomeAttr() == randomPointer.getSomeAttr()){
        objectPtrDelete = pointer;
        break;
    }
    i++;
}
    
// Shrinking the C-array with this for loop, shifting left
for (int j = i; j < N-1; j++)
    stuff[j] = stuff[j + 1];

Can the last loop be converted into a Pointer loop, if yes, how is this properly done? Note, the names are fictional i.e. something imaginary. I have implemented something similar, but, I would like to understand how can I convert the last loop to a pointer for loop that does the same operation.

Make this:

for (int j = i; j < N-1; j++)
    stuff[j] = stuff[j + 1];

Into a Pointer loop.

11
  • 1
    What is a "pointer loop"? Commented Oct 2, 2020 at 20:56
  • I do not know, stackoverflow.com/questions/33829566/for-loop-with-pointer-in-c. But, is it correct and is that the way you do it? Commented Oct 2, 2020 at 20:58
  • 1
    If you use pointers instead of indices not much changes. You simply need to figure out what you use as the condition (presumably something like ptr != a + N and make sure that you dereference correctly in the body. Commented Oct 2, 2020 at 21:00
  • 2
    @Albin M This int[] a = new int[N] is not a valid C++ record. Commented Oct 2, 2020 at 21:01
  • I have a Pointer array, SomeClass* stuff; This is initiated: stuff = new SomeClass[10]; Commented Oct 2, 2020 at 21:04

2 Answers 2

1

For starters this construction (without an ending semicolon)

int[] a = new int[N]

is invalid in C++.

It should look like

int *a = new int[N];

If I have understood your question correctly you mean something like the following

for ( auto prev = a, next = a + 1; next != a + N; ++next )
{
    *prev++ = *next;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Vlad, see my update. I apologize for not clarifying earlier.
@AlbinM What was changed?
@VladfromMoscow just the type of the array and the name of the variable
0

(edited to take into account your changes)

if I well understand what you want, having

SomeClass* stuff;

you can replace

for (int j = i; j < N-1; j++)
   stuff[j] = stuff[j + 1];

by

for (SomeClass * p =  stuff + i; p < stuff + N-1; p++)
    *p = *(p + 1);

or to easily manages changes concerning the type :

for (auto p =  stuff + i; p < stuff + N-1; p++)
    *p = *(p + 1);

etc

5 Comments

@AlbinM I updated my answer, just the type and names changes
Bruno, will that still shrink the array?
Your code is confusing, where's int j now?
@AlbinM what you mean shrink the array ? its size is unchanged, you just move elements
@AlbinM ah yes, sorry, I missed to replace a j by p, corrected