1、输入迭代器 std::istream_iterator

#include <iterator>
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char* argv[]) 
{
    istream_iterator<int> input_it(cin), end;
    
    vector<int> nums(input_it, end);
    for (int x : nums) 
        cout << x << " ";
}

 

2、输出迭代器 std::ostream_iterator

#include <iterator>
#include <vector>
#include <iostream>

using namespace std;

int main() 
{
    vector<int> nums = {1, 2, 3};
    
    copy(nums.begin(), nums.end(),  
            ostream_iterator<int>(cout, " "));
    
    cout << endl;
}

 

3、前向迭代器 std::forward_list

#include <forward_list>
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) 
{
    forward_list<int> flist = {10, 20, 30};
    forward_list<int>::iterator  it = flist.begin();
    cout << *it << endl;  // 输出 10

    it++;  // 前向移动合法
    cout << *it << endl;  // 输出 20

    //it-- 或者it = it +2不合法
    return 0;
}

 

4、双向迭代器  std::list      std::set      std::map

#include <list>
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) 
{
    list<int> myList = {1, 2, 3, 4, 5};
    auto it = myList.begin();
    for (it = myList.begin();  it != myList.end();  ++it) 
    {
        std::cout << *it << " ";
    }

    cout << endl;
    cout << *(--it) << endl;

    // cout << endl;

    // for (it = myList.rbegin();  it != myList.rend();  ++it) 
    // {
    //     std::cout << *it << " ";
    // }    

    return 0;
}

 

5、随机访问迭代器 std::vector    std::deque    std::array   std::string

#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) 
{
    vector<int> myVector = {10, 20, 30, 40, 50};

    // 直接通过下标访问
    cout << myVector[2] << endl;  // 输出: 30

    // 通过迭代器运算访问
    auto it = myVector.begin();
    cout << *(it + 4) << endl;  // 输出: 30
}

 

posted on 2025-05-07 10:14  轩~邈  阅读(13)  评论(0)    收藏  举报