int 有效,但字符串::size_type不起作用

int works but string::size_type doesn't

本文关键字:size type 不起作用 字符串 有效 int      更新时间:2023-10-16
    #include <string>
    #include <iostream>
    using namespace std;
    const string& strReverse(const string&);
    int main() {
        cout << strReverse("POT") << endl;
    }
    const string& strReverse(const string& s) {
        static string ret;
        ret = "";

        for(string::size_type i = s.length()-1; i >= 0; --i) {
            ret += s[i];
        }
        return ret;
    }

上面的代码会导致程序在运行时崩溃。但是,如果我更改i的类型以int它有效。

为什么?我认为使用string::size_type比使用特定类型(例如int)"更安全"。使用 auto 也会导致程序崩溃。

我认为 string::size_type 中的类型可能与数组索引不兼容,所以我尝试将索引i转换为 int ,但这也不起作用。

这是因为

string::size_type是无符号的,所以 for 循环的终止条件i >= 0将始终为真。您的选择:

  1. 使用 int;

  2. 继续使用 size_type 但更改循环:

    for(string::size_type i = s.length(); i > 0; --i) {
        ret += s[i-1];
    }
    

或者我最喜欢的选择:

  1. 使用std::reverse_iterator并在一行中完成整个操作:

喜欢这个:

std::string ret(s.rbegin(), s.rend());

一些补充意见:

  1. 不要返回对静态字符串的引用。它不是线程安全的。按值返回(即返回std::string,而不是const std::string&)。

  2. 为了获得更好的性能,请为字符串预分配所需的容量:ret.reserve(s.size());

您应该按值传递和返回std::string

std::string strReverse( std::string s)
{
     for( size_t i = 0; i < s.size() / 2; ++i )
         std::swap( s[i], s[s.size()-i-1] );
     return s;
}

这将使您的函数同时更简单、更正确。

相关文章: