简体   繁体   English

i++ 还是 ++i 更适合这个程序?

[英]Is i++ or ++i better for this program?

i'm trying to create a program which checks if input is is an int or a string.我正在尝试创建一个程序来检查输入是 int 还是 string。

This is the code:这是代码:

// 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 wanted to ask that whether i++ or ++i is better for this loop and why?我想问一下 i++ 或 ++i 是否更适合这个循环,为什么?

for (int i = 0; i < s.length(); i++) 
        if (isdigit(s[i]) == false) 
            return false;

THANK YOU!谢谢你!

I prefer the form ++i in C++, because i may be an iterator or other object with overloaded operator++ .我更喜欢 C++ 中的++i形式,因为i可能是迭代器或其他具有重载operator++的 object 。 In those cases, the form i++ generates a temporary object to hold the previous value of i , while the form ++i does not.在这些情况下, i++形式会生成一个临时 object 来保存i的先前值,而++i形式不会。 The compiler may optimize away that temporary object, but it's not required to, and in some cases may not be allowed to.编译器可能会优化掉该临时 object,但这不是必需的,在某些情况下可能不允许这样做。

So, ++i is slightly better than i++ as the former need not retain the initial value and recheck it.因此, ++ii++略好,因为前者不需要保留初始值并重新检查它。 It is one of the very few instances where time optimization and memory optimization occur simultaneously.这是时间优化和 memory 优化同时发生的极少数情况之一。 But the difference is too small to be noted, just 4 bytes.但是差异太小了,无法注意到,只有 4 个字节。 Also, the time difference is negligibly small.而且,时间差小到可以忽略不计。

You would essentially get the same answer in your example but might receive a minute time and memory optimization while using ++i .在您的示例中,您基本上会得到相同的答案,但在使用++i时可能会收到一分钟时间和 memory 优化。

Since the datatype of i is int, it doesn't matter if you use i++ or ++i.由于 i 的数据类型是 int,因此使用 i++ 或 ++i 都没有关系。 If its a large class iterator, ++i is faster than i++.如果它是一个大的 class 迭代器,++i 比 i++ 快。 Its a good practice to use ++i.使用 ++i 是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM