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根据输入而定;

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;
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM