Marc.2377 Marc.2377 - 3 months ago 18
C Question

Array Indices vs Array Elements

This is a sort of meta-question related to this question: How do I write a branchless std::vector scan?.

The question originally stated (emphasis mine):


I have a
std::vector<int> data
; and I want to find all the array
indexes
that are less than 9 and add them to a result vector.


Then I edited it to:


I have a
std::vector<int> data
, and I want to find all elements that
are less than 9 and add them to a result vector.


And then another user edited it to:


I have a
std::vector<int> data
and I want to find all array indices at
which the elements
are less than 9 and add them to a result vector.


I flagged it for a moderator to revert this, stating:


I reworded this question (stackoverflow.com/posts/38798841/revisions)
with the main goal of replacing "array indexes" with "elements", since
that is what's actually being asked - and referring to
"indexes/indices" in this context causes some confusion. However, user
Aconcagua has overturned this crucial part of my edit. It's my belief
that his latest edit should be rolled back.


and it was declined with reason:


Aconcagua's edit is correct; the user is collecting array indicies,
not the array elements themselves


.

Now, I don't quite understand what the moderator says - "the user is collecting array indicies". The way I see it, an index is the location of an element within an array. For example, in the C language:

char array[] = {'t', 'e', 's', 't'};
int index = 1;
char element = array[index];
printf('%c', element);


I simply don't see how, or why, he would be collecting "indices" instead of "elements". Can someone clarify this so I can really understand it?

Thanks.

Answer

In the example code at the top of the linked question:

for (int i = 0; i < data.size(); ++i)
    if (data[i] < 9)
        r.push_back(i);

Notice that i is being added to the vector, not data[i].

i is the index of the interesting element, and is what is being stored, not the value stored at data[i], which is the element in the data vector.

Comments