ITHelpself / CPlusPlus

0 stars 0 forks source link

9. iterator (dont complete) #9

Open ITHelpself opened 3 years ago

ITHelpself commented 3 years ago

auto my_iterator = my_vector.begin(); // position
auto my_value = *my_iterator; // value
ITHelpself commented 3 years ago

auto first = my_vector.begin();
++first; // advance the iterator 1 position
GoalKicker.com – C++ Notes for Professionals 37
std::advance(first, 1); // advance the iterator 1 position
first = std::next(first); // returns iterator to the next element
std::advance(first, -1); // advance the iterator 1 position backwards
first = std::next(first, 20); // returns iterator to the element 20 position
forward
first = std::prev(first, 5); // returns iterator to the element 5 position
backward
auto dist = std::distance(my_vector.begin(), first); // returns distance between two iterators.
ITHelpself commented 3 years ago

template<class Iter>
Iter find(Iter first, Iter last, typename std::iterator_traits<Iter>::value_type val) {
 while (first != last) {
 if (*first == val)
 return first;
 ++first;
 }
 return last;
}
ITHelpself commented 3 years ago

template <class BidirIt>
void test(BidirIt a, std::bidirectional_iterator_tag)
{
    std::cout << "Bidirectional iterator is used" << std::endl;
}
template <class ForwIt>
void test(ForwIt a, std::forward_iterator_tag)
{
    std::cout << "Forward iterator is used" << std::endl;
}
template <class Iter>
void test(Iter a)
{
    test(a, typename std::iterator_traits<Iter>::iterator_category());
ITHelpself commented 3 years ago

//vector iterator
#include <vector>
#include <iostream>
int main()
{
    std::vector<int> v = {1, 2, 3, 4, 5}; //intialize vector using an initializer_list
    for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)
    {
        std::cout << *it << " ";
    }
    return 0;
}
ITHelpself commented 3 years ago

// Create a map and insert some values
std::map<char, int> mymap;
mymap['b'] = 100;
mymap['a'] = 200;
mymap['c'] = 300;
// Iterate over all tuples
for (std::map<char, int>::iterator it = mymap.begin(); it != mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';
ITHelpself commented 3 years ago

std::vector<int> v{1, 2, 3, 4, 5};
for (std::vector<int>::reverse_iterator it = v.rbegin(); it != v.rend(); ++it)
{
 cout << *it;
} // prints 54321