tags:

views:

89

answers:

4
const int NUMB = 4;
int n[] = {5,6,7,8};

// create a vector of strings using the n[] array
vector<int> partnums(n, n + NUMB);

The class functions vector name(src.begin, src.end)

Create a vector initialized with elements from a source container beginning at src.begin and ending at scr.end

According to the book,

The vector partnums is declared as a vector type int and initialized with elements from the n array, starting with the first array element n[0], and ending with the last array element, located at position n + NUMB.

I don't get it, still. "Located at position n+ NUMB, isn't the index starts at 0? Or the compiler knows that this src.end is referring to position 1 (scr.begin), and count that from that position in the array n, and count to the 4th position)?

Thank you

+1  A: 

The n + NUMB is a pointer to the last element + 1 or IOW one position beyond the size of the array.

when copying it starts at n + 0 and copies up to last element

Anders K.
+4  A: 

From cplusplus.com:

Input iterators to the initial and final positions in a sequence. The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element pointed by last.

n points to the beginning of the array, and n + NUMB acts as pointer arithmetic, effectively incrementing n by sizeof(int) * NUMB. So n + NUMB points to the "end" of the array (the first address beyond the array, really). Since the "end" given in the initializer is non-inclusive, this covers all of the elements in the array (indexes 0-3, or indexes 0 to ( NUMB - 1 ) in the general case).

eldarerathis
+5  A: 

The C++ standard library uses a convention that the 'end' iterator is actually referring to one element past the end, so in your case 'begin' would be the 0th position and 'end' the fourth (not third) position.

What is confusing in your citation above is that n + NUMB is referred to as the last element in the array, which is incorrect. It is the (fictional) element after the last element in the array and simply used as an end marker.

Timo Geusch
+2  A: 

One of the best articles I have found on this is here explaining the concept of "one past the end"

Chubsdad