int 有效,但字符串::size_type不起作用
int works but string::size_type doesn't
#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
将始终为真。您的选择:
使用 int;
继续使用 size_type 但更改循环:
for(string::size_type i = s.length(); i > 0; --i) { ret += s[i-1]; }
或者我最喜欢的选择:
- 使用
std::reverse_iterator
并在一行中完成整个操作:
喜欢这个:
std::string ret(s.rbegin(), s.rend());
一些补充意见:
不要返回对静态字符串的引用。它不是线程安全的。按值返回(即返回
std::string
,而不是const std::string&
)。为了获得更好的性能,请为字符串预分配所需的容量:
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;
}
这将使您的函数同时更简单、更正确。
相关文章:
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 大于65535的C++数组[size]引发不一致的溢出
- 为什么(-1)%vector::size()总是返回0
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 在 QVector<std::unique_ptr 上使用 std::find<Type>>
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 控制到达非空函数clang(-Wreturn-type)的末尾
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- 警告的原因是什么:"when type is in parentheses, array cannot have dynamic size"?
- 调用 list.size() 方法给出错误"expression must have class type"
- vtkTypeTraits.h 错误:"Type long is not 4 or 8 bytes in size."
- C++/ASM - "Operand size conflict" , "Improper operand type"
- 提升精神语法错误 - "no type named ‘size’ in ‘struct boost::spirit::unused_type’"
- 如何在 c++11 中使用容器 std::array<type, size> 用于多维数组?
- OpenCV 错误:断言失败 (src1.size == dst.size && dst.type() == CV_8U) in cvInRangeS
- "error: request for member ‘size’ in ‘a’, which is of pointer type"但我不认为这是一个指针
- new(size, value) Type[0]返回的指针是否合法,是否可以用来构建数组?