c++ - i++或++ i更适合此程序吗?

标签 c++ string function for-loop integer

我正在尝试创建一个程序来检查输入是否为整数或字符串。
这是代码:

// CPP program to check if a given string 
// is a valid integer 
#include <iostream> 
using namespace std; 
  
// Returns true if s is a number else false 
bool isNumber(string s) 
{ 
    for (int i = 0; i < s.length(); i++) 
        if (isdigit(s[i]) == false) 
            return false; 
  
    return true; 
} 
  
// Driver code 
int main() 
{ 
    // Saving the input in a string 
    string str = "6790"; 
  
    // Function returns 1 if all elements 
    // are in range '0-9' 
    if (isNumber(str)) 
        cout << "Integer"; 
  
    // Function returns 0 if the input is 
    // not an integer 
    else
        cout << "String"; 
} 
我想问问i ++或++ i对于此循环是否更好,为什么?
for (int i = 0; i < s.length(); i++) 
        if (isdigit(s[i]) == false) 
            return false;
谢谢!

最佳答案

我更喜欢C++中的++i形式,因为i可能是迭代器或其他带有重载operator++的对象。在这些情况下,i++格式会生成一个临时对象来保存i的先前值,而++i格式则不会。编译器可能会优化掉该临时对象,但这不是必需的,在某些情况下可能不允许这样做。
因此,++i略优于i++,因为前者无需保留初始值并重新检查它。它是极少数同时发生时间优化和内存优化的实例之一。但是差异太小了,无法注意到,只有4个字节。而且,时间差可以忽略不计。
在示例中,您基本上会得到相同的答案,但在使用++i时可能会花费一分钟的时间和内存优化。

关于c++ - i++或++ i更适合此程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62605887/

相关文章:

javascript 函数未被调用/无法从 html 表单工作

c++ - 在 Vector C++ 中查找最后定义的元素

c++ - Solaris 5.10 x86 CC 链接器错误 : ld: fatal: library -lcryptoki: not found

c++ - 如何合并两个 LPCWSTR?

python - 属性错误 : 'str' object has no attribute 'items'

python - 在我的类中调用函数不起作用

python - 如何在 Python(不使用 MedPy)或 C 中将 *.mha 文件转换为 *.nii 文件?

python - 我没有得到匹配的字符串

c - 当我在我的计算机和学校计算机上编译时,消息不一样

c++ - 函数没有返回正确的结果