Skip to content

Commit 600851d

Browse files
Update vector.md
1 parent 73906fd commit 600851d

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

‎STL/vector.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,48 @@ We can declare a vector in several ways. Let us see some of them at a glance and
314314
| **rbegin()** <br> `v.rbegin()` | Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first. |
315315
| **rend()** <br> `v.rend()` | Returns a reverse iterator pointing to the first element in the vector (reverse end). |
316316

317+
Let's see their uses through code:-
318+
319+
```cpp
320+
vector < int > v {1, 2, 3, 4, 5};
321+
322+
cout << "Using begin() & end(): ";
323+
for(auto i = v.begin(); i != v.end(); i++) {
324+
cout << *i << " ";
325+
}
326+
cout << endl;
327+
328+
cout << "Using rbegin() & rend(): ";
329+
for(auto i = v.rbegin(); i != v.rend(); i++) {
330+
cout << *i << " ";
331+
}
332+
cout << endl;
333+
```
334+
335+
Output:
336+
Using begin() & end(): 1 2 3 4 5
337+
Using rbegin() & rend(): 5 4 3 2 1
338+
339+
In this code, `i` is used as an iterator. We have used auto to keep it simple. If we do not want to use auto, we have to declare an iterator to vector like this - `vector < int >::iterator i` and a reverse iterator like this `vector < int >::reverse_iterator j;`. The we can use `i` in the first loop and `j` in the second loop.. Then the code will be like :-
340+
341+
```cpp
342+
vector < int > v {1, 2, 3, 4, 5};
343+
vector < int >::iterator i;
344+
vector < int >::reverse_iterator j;
345+
346+
cout << "Using begin() & end(): ";
347+
for(i = v.begin(); i != v.end(); i++) {
348+
cout << *i << " ";
349+
}
350+
cout << endl;
351+
352+
cout << "Using rbegin() & rend(): ";
353+
for(j = v.rbegin(); j != v.rend(); j++) {
354+
cout << *j << " ";
355+
}
356+
cout << endl;
357+
```
358+
317359
***
318360

319361
### Important Capacity Functions

0 commit comments

Comments
 (0)