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