C++:迭代器(iterator)使用的几点

#include <iomanip>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
using std::vector;

int main()
{
    string word("asdfgh"); //初始化字符串word
    vector<string>ivec(10,"asdfgh");//ivec包含了10个元素
    while (cin >> word) //遇到空白停止
    {
        /*
        begin 成员函数返回指向容器中第一个元素;
        end 成员函数返回的不是指向最后一个元素的迭代器,而是指向最后一个元素后面的位置的迭代器;

        transform(first1,last1,first2,result,binary_op);
        first1是第一个容器的首迭代器,last1为第一个容器的末迭代器,
        first2为第二个容器的首迭代器,result为存放结果的容器;
        */
        transform(word.begin(), word.end(), ivec.begin(), toupper);
        //ivec.push_back(word);
    }
    for (auto& i : ivec) //i是string类型
    {
        cout << i << endl;
    }
}

tansform函数将迭代器区间[first,last)中元素,执行一元函数(有一个输入变量)对象op操作,交换后的结果放在[result,result+(last-first))区间中。

ivec.size = 10;

word.size根据输入而定;

C++:迭代器(iterator)使用的几点

transform 将ivec区间【0,1】的元素替换将小写字符串转换为大写并逐行输出:
#include <iomanip>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
using std::vector;

int main()
{
    string word("asdfgh"); //初始化字符串word
    vector<string>ivec;
    while (cin >> word) //遇到空白停止
    {

        transform(word.begin(), word.end(), word.begin(), toupper);
        ivec.push_back(word);
    }
    for (auto& i : ivec) //i是string类型
    {
        cout << i << endl;
    }
}

C++:迭代器(iterator)使用的几点


原文链接: https://www.cnblogs.com/chenzexin/p/12546869.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/194698

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午6:46
下一篇 2023年2月12日 下午6:46

相关推荐