#include <iostream>
#include <string>
int main() {
using namespace std;
cout << "Please Enter a string:\n";
string word;
cin >> word;
// 就地反轉:雙指針交換
for (int i = 0, j = word.length() - 1; i <= j; ++i, --j) {
char temp = word[i]; // 內層聲明:每次循環分銷毀,略慢但作用域最小
// char temp = word[i]; // 外層聲明:僅分配一次,性能略優
word[i] = word[j];
word[j] = temp;
}
cout << word << endl;
return 0;
}
| 特性 | std::string | C 風格 (char*/char[]) |
|---|---|---|
| 頭文件 | <string> | <cstring> / <string.h> |
| 內存管理 | 自動 (RAII) | 手動 (malloc/free/new/delete) |
| 長度獲取 | .size() / .length() O(1) | strlen() O(n) |
| 邊界檢查 | .at() 拋出異常 | 無,極易越界 |
| 拼接/比較 | 運算符重載直觀 | strcat/strcmp 易錯 |
| 動態擴容 | 自動 | 需手動重新分配 |
建議:現代 C++ 優先使用 std::string,僅在與 C API 交互時轉換。
length() 為兼容 C 風格習慣,size() 符合 STL 容器統一接口// 方式 A:循環外聲明(推薦性能敏感場景)
char temp;
for (int i = 0, j = n-1; i <= j; ++i, --j) {
temp = word[i]; word[i] = word[j]; word[j] = temp;
}
// 方式 B:循環內聲明(推薦現代 C++,作用域最小化)
for (int i = 0, j = n-1; i <= j; ++i, --j) {
char temp = word[i]; // 每次迭代構造/析構
word[i] = word[j]; word[j] = temp;
}
結論:對於 POD 類型(如 char),編譯器優化後無差異;對於複雜類型,方式 B 避免默認構造+賦值的開銷,現代編譯器均能優化。優先選擇方式 B,符合「最小作用域」原則。
數組/字符串下標從 0 開始,合法範圍 [0, length-1]。反轉循環條件 i <= j 或 i < j 均可,關鍵是初始 j = length() - 1。
std::reverse內部使用雙向迭代器,對隨機訪問迭代器(如 string)特別優化,性能不遜手寫循環,代碼更安全、可讀。完整最佳實踐版本
#include <iostream> #include <string> #include <algorithm> int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::string word; std::cout << "Enter string: "; if (std::getline(std::cin, word)) { // 支持含空格字符串 std::reverse(word.begin(), word.end()); std::cout << "Reversed: " << word << '\n'; } return 0; }