C++ Iterators: Input Iterator
An input iterator is a type of iterator used to iterate through a sequence of values in a read-only manner. It is used to traverse any container which can be read from like a stream.
Syntax
iterator_name begin() const;
iterator_name end() const;
In the above syntax, the begin()
function returns an iterator pointing to the first element in the sequence, while the end()
function returns an iterator pointing to the position just past the last element.
Example
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myVector = {1, 2, 3, 4, 5};
vector<int>::iterator it;
for (it = myVector.begin(); it != myVector.end(); ++it) {
cout << *it << " ";
}
return 0;
}
Output
1 2 3 4 5
Explanation
In the above example, we are using a vector as a container. We first declare an iterator object 'it' and initialize it to the beginning of the vector using the begin()
function. We then use this iterator to traverse the vector and print each element one by one.
Use
Input iterators are used to traverse through a container in a read-only manner. They can be used to perform operations on the container elements or to extract data from the container.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main() {
ifstream inputFile("input.txt");
vector<string> lines;
string line;
while (getline(inputFile, line)) {
lines.push_back(line);
}
for (vector<string>::iterator it = lines.begin(); it != lines.end(); ++it) {
cout << *it << endl;
}
inputFile.close();
return 0;
}
In the above example, we are using an input iterator to read lines from a text file and store them in a vector. We then use the same iterator to print out each line of the vector.
Important Points
- Input iterators are used for read-only access to a container.
- They use the
begin()
andend()
functions to traverse through a container. - Input iterators are used for operations or to extract data from container elements.
Summary
In summary, input iterators in C++ are used to traverse through a container in a read-only manner. They are useful when you need to perform operations on the container elements or extract data from them. With the help of input iterators, you can easily access the contents of the container and manipulate them in different ways.