首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ vector 迭代器配合 toupper:需逐字符轉換而非整體字符串

     編輯:程式設計綜合問答

問題:toupper(int) 僅接受單字符,不能直接作用於 std::string。需遍歷字符串每個字符調用 toupper。

錯誤代碼

vector<string> text{"hello world"};
for (auto it = text.begin(); it != text.end() && !it->empty(); ++it) {
    *it = toupper(*it);  // 編譯錯誤:無法將 string 轉為 int
    cout << *it << endl;
}

正確做法:封裝字符串大寫函數

#include <iostream>
#include <vector>
#include <string>
#include <cctype>

using namespace std;

string toUpper(const string& s) {
    string r = s;
    for (char& c : r) c = toupper(static_cast(c));
    return r;
}

int main() {
    vector text = {"hello world", "c++ primer"};
    for (auto it = text.begin(); it != text.end() && !it->empty(); ++it) {
        cout << toUpper(*it) << endl;
    }
    return 0;
}

關鍵點

  • toupper 參數為 int (實際為 unsigned char 或 EOF),返回轉換後的 int。
  • static_cast(c) 避免負值導致未定義行為 (針對非 ASCII 字符)。
  • 原字符串不修改,返回新字符串,符合函數式風格。

C++20 範圍庫寫法 (更簡潔)

#include <ranges>
#include <algorithm>

for (auto& s : text | views::take_while([](auto& x){ return !x.empty(); })) {
    ranges::transform(s, s.begin(), [](char c){ return toupper((unsigned char)c); });
    cout << s << endl;
}

第二問題:string 迭代器判斷 !it->empty() 報錯

若 text 類型改為 string (而非 vector),則 it 是 char 迭代器,it->empty() 無意義 (char 無 empty() 方法)。string 本身用 text.empty() 判斷整體是否為空。

理解迭代器指向的元素類型,才能正確調用成員函數。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved