Reputation: 48916
In the C++ Primer book, Chapter (3), there is the following for-loop that resets the elements in the vector to zero.
vector<int> ivec; //UPDATE: vector declaration
for (vector<int>::size_type ix = 0; ix ! = ivec.size(); ++ix)
ivec[ix] = 0;
Is the for-loop really assigning 0
values to the elements, or do we have to use the push_back
function?
So, is the following valid?
ivec[ix] = ix;
Thanks.
Upvotes: 1
Views: 3234
Reputation: 361264
Is the for-loop really assigning 0 values to the elements? Or, we have to use the push_back finction?
ivec[ix] =0
updates the value of existing element in the vector, while push_back
function adds new element to the vector!
So, is the following valid?
ivec[ix] = ix;
It is perfectly valid IF ix < ivec.size()
.
It would be even better if you use iterator
, instead of index. Like this,
int ix = 0;
for(vector<int>::iterator it = ivec.begin() ; it != ivec.end(); ++it)
{
*it = ix++; //or do whatever you want to do with "it" here!
}
Use of iterator
with STL is idiomatic. Prefer iterator over index!
Upvotes: 5
Reputation: 31425
Yes, assuming ix is a valid index, most likely: you have a vector of int though and the index is size_type. Of course you may want to purposely store -1 sometimes to show an invalid index so the conversion of unsigned to signed would be appropriate but then I would suggest using a static_cast.
Doing what you are doing (setting each value in the vector to its index) is a way to create indexes of other collections. You then rearrange your vector sorting based on a predicte of the other collection.
Assuming that you never overflow (highly unlikely if your system is 32 bits or more) your conversion should work.
Upvotes: 0
Reputation: 3252
The purpose of this for loop is to iterate through the elements of the vector. Starting at element x (when ix is 0) up to the last element (when ix is ivec.size() -1).
On each iteration the current element of the vector is set to 9. This is what the statement
ivec[ix] = 0;
does. Putting
ivec[ix] = ix;
in the for loop would set all the elements of the vector to their position in the vector. i.e, the first element would have a value of zero (as vectors start indexing from 0), the second element would have a value of 1, and so on and so forth.
Upvotes: 0
Reputation: 36477
Using the array brackets the vector object acts just like any other simple array. push_back()
increases its length by one element and sets the new/last one to your passed value.
Upvotes: 0
Reputation: 372664
Yes, you can use the square brackets to retrieve and overwrite existing elements of a vector. Note, however, that you cannot use the square brackets to insert a new element into a vector, and in fact indexing past the end of a vector leads to undefined behavior, often crashing the program outright.
To grow the vector, you can use the push_back, insert, resize, or assign functions.
Upvotes: 2