Reputation: 35
I'm trying to learn C++ vectors.. Here is the code:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector <int> vec;
for(int i=0; i<=10; i++){
vec.push_back(i);
}
for(auto i=vec.begin(); i!=vec.end();i++){
cout<<*i<<" ";
}
}
Can anybody tell me what this part is?
for(auto i=vec.begin(); i!=vec.end();i++){
cout<<*i<<" ";
}
I've searched the Internet but couldn't find a clear explanation.
Ok, it prints the numbers that we put it in the vector, but can I get a more technical explanation?
Upvotes: 1
Views: 77
Reputation:
That part simply prints all the elements of the vector. auto
automatically determines what data structure it is given the parameters that define it. In this case, it is being used as a vector<int>::iterator
. Mostly, this is used in other data structures, such as a map
or a set
, since those don't support random access. In a vector, you can simply do
for(int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
Upvotes: 1
Reputation: 5766
for(auto i=vec.begin(); i!=vec.end();i++){
cout<<*i<<" ";
}
This is just the iterators in C++.
begin()
function is used to return an iterator pointing to the first element of the vector.
Similarly, end()
function is used to return an iterator pointing past the last element of the vector.
auto
just deduces the type of the variable i
. You could have also specified it as std::vector<int>::iterator i = vec.begin()
. That's the type of the iterator you are using to loop over the vector.
In the above piece of code, you are basically iterating from the beginning of the vector until the end of the vector.
Inside the loop, you are just dereferencing the iterator and printing the value at the current position where the iterator is.
What the above piece of code is doing is basically the same as the following type of loop, which uses indexing to loop over the array:
for(size_t i = 0; i != vec.size() ; i++){
cout << vec[i] << " ";
}
You should read more about iterators, as they are a core concept in C++. You can read more about them here:
Upvotes: 2
Reputation: 122228
This is an iterator to the first element in the vector: vec.begin()
An iterator to one-past the last element of the vector: vec.end()
auto
deduces the type of i
from vec.begin()
, its an iterator. We really do not need to care about the exact type.
We only need to know that we can increment it: i++
.
And compare two iterators with each other to check if we are at the end: i != vec.end()
.
And we can derference iterators to get the element the "point to": *i
.
Without iterators the loop could be written as:
for (size_t i=0; i<vec.size(); ++i) {
std::cout << vec[i];
}
Upvotes: 2