-1

I am not proficient in C++ but I am converting a short script to PHP

for(auto it = First; it != Last; ++it)
{
    Result += *it;
}

From this snippet, I can speculate this simply means

Result = Result + it 

where * is a reference to the pointer of the loop.

That said I see this symbol used outside of loops and in some cases I see variables without this symbol both in and outside of loops which puts holes in my theory.

Again I am trying to RTFM but I am unsure what I am searching for.

myol
  • 8,857
  • 19
  • 82
  • 143

2 Answers2

1

Both First and Last are iterator objects, representing a generalization of pointers in C++ Standard Library. Additionally, the two iterators reference the same collection, and Last can be reached from First by incrementing the iterator*.

Result is some sort of accumulator. If it is of numeric type, += means Result = Result + *it, where *it is whatever the iterator is pointing to. In other words, Result accumulates the total of elements of the collection between First, inclusive, and Last, exclusive. If First points to the beginning of an array and Last points to one-past-the-end of an array of numeric type, your code would be equivalent to calling PHP array_sum() on the array.

However, Result is not required to be numeric. For example, it could be a std::string, in which case += represents appending the value to the string.

* In terms of pointers and arrays this would be "pointing to the same array," and "Last points to a higher index of the array than First."

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

I believe your speculation is incorrect.

it, first and last are either iterators or pointers. Iterators are C++ objects that can be used to iterator over containers. For basic usage, they behave much like pointers, and can be dereferenced the same way.

For example:

std::vector<int> myList;

...

// Search for the number 10 in the list.
std::vector<int>::iterator it = std::find(myList.begin(), myList.end(), 10);

// If the number 10 was found in the list, change the value to 11.
if (it != myList.end())
    *it = 11;  //< Similar to pointer syntax.

In your specific example, the Result variable has a value added to it. To get that value, your code uses the * operator to get the value from the iterator.

The same concept applies to pointers. although iterators and pointers are very different concepts, accessing their values is very similar.

Karl Nicoll
  • 16,090
  • 3
  • 51
  • 65