简体   繁体   中英

Loop repeats for no reason?

In the following code the cout statement (sometimes) repeats without exiting the if statement and without incrementing j in j++. Sometimes the loop works just as expected (j++ gets incremented once for each cout and the statement exits). I've looked at this (and looked ...) and can't figure out what I did wrong. Any ideas?

   void SlipHash::outputHashTable() {
      ios_base::fmtflags fmtflg = cout.flags();
      const int size = min(nEntries, tableSize);
      for ( int i = 0, j = 0; j < size; i++ ) {
         if (hashTable[i]) {
            j++;
            cout << left << setw(27) << "SlipHash::outputHashTable[" << dec << i << "] "
                 << hex << hashTable[i] << endl;
         }
      }
      cout.flags(fmtflg);
   }; // void SlipHash::outputHashTable()
for ( int i = 0, j = 0; j < size; i++ ) {

It seems that you've mistyped;;

for ( int i = 0, j = 0; j < size; j++ ) {
//                                ^

or

for ( int i = 0, j = 0; i < size; i++ ) {
//                      ^

will be correct.

When you enter in the if statement you can't have a cout without incrementation of the j var. Are you sure nEntries and tableSize and right values ? If not you can use values in memory out of the hashTable[size_table] field if value is superior, or even create infinite loop if inferior because j never reach the size var

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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