Могу ли я узнать, почему этот код не дает никаких результатов? - PullRequest
1 голос
/ 21 июня 2020

Пожалуйста, помогите мне решить запрос, что этот код работает бесконечно в определенной строке.

Он не дает никакого вывода, поскольку в конце кода я пишу код для печати вектора. Даже после того, как я присвоил какое-либо значение вектору «result» вручную, он все равно не дает никаких результатов. почему так?

#include<bits/stdc++.h>
using namespace std;

bool authorize(int strValue, int value, int M) 
{
   long int newValue = (strValue - (value * 131) % M);
   if (newValue >= 48 && newValue <= 57)
      return true;
   if (newValue > 65 && newValue <= 90)
      return true;
   if (newValue >= 97 && newValue <= 122)
      return true;
   return false;
}

int hashingfunct(string str, int M) 
{
   long int P, F, sum = 0;
   int len = str.length();
   for (int i = 0; i < len; i++)
   {
      P = pow(131, len - i - 1);
      F = (int)str[i];
      sum += (F * P) % M;
   }
   sum = sum % M;
   return sum;
}

int main()
{
   int n = 5;
   string str1, str2;
   vector<vector<string> > events;
   for (int i = 0; i < n; i++) {
      cin >> str1 >> str2;
      vector<string > temp;
      temp.push_back(str1);
      temp.push_back(str2);
      events.push_back(temp);
   }
   for (int i = 0; i < n; i++) {
      cout << events[i][0] << events[i][1];
   }
   /*
   INPUT FORMAT:
   setpassword 1
   setpassword 2
   setpassword 3
   authorize 49
   authorize 50
   */
   vector<int> result;
   int j = 0;
   long int m = pow(10, 9);
   long int M = m + 7;
   long int value, strValue;
   for (int i = 0; i < events.size(); i++)
   {
      strValue = stoi(events[i][1]);
      if (events[i][0] == "setPassword") {
         value = hashingfunct(events[i][1], M);
      }
      else if (strValue == value)
         result[j++] = 1;
      else if (authorize(strValue, value, M))
         result[j++] = 1;
      else
         result[j++] = 0;
   }

   for (int i = 0; i < result.size(); i++) {
      cout << result[i];
   }
}

Ответы [ 2 ]

3 голосов
/ 21 июня 2020

Ваша программа имеет полное неопределенное поведение.

Давайте начнем с первой проблемы. В следующем контрольном коде

long int value, strValue;  // not initialised
for (int i = 0; i < events.size(); i++)
{
   // ... 
   // here it should have been "setpassword" (i.e. all are small letters)
   if (events[i][0] == "setPassword")
   {
       // if the check fails the `value` never get initialised!
       value = hashingfunct(events[i][1], M);
   }
   // If the `value` not been initialised, check happens with any garbage value here!
   else if (strValue == value) 

   // ...other code
}

вы проверяете, соответствует ли строка "setPassword" вместо "setpassword" (т.е. см. В векторе events, все строки - маленькие буквы).

Если что-то пойдет не так, value никогда не будет инициализирован, что означает, что он содержит любое значение мусора и, следовательно, проведение этой проверки else if (strValue == value) может вызвать любое поведение в вашу программу (также известную как Undefined Behavior ) .

Во-вторых, vector<int> result; пусто в начале. Следовательно, доступ к элементам через std::vector::operator[] позже

result[j++] = 1;
// ...
result[j++] = 1;
// ...
result[j++] = 0;

запускает доступ за пределы (UB) . Там вам нужно просто result.emplace_back(/*value*/); или result.push_back(/*value*/);, и нет необходимости в редутантной переменной j.

Короче, вам нужно

#include <iostream>
#include <vector>
#include <string>

// ..other functions
int main()
{
   std::vector<std::vector<std::string> > events { 
      {"setpassword", "1"}, // can be also user input, like in your example
      {"setpassword", "2"},
      {"setpassword", "3"},
      {"authorize", "49" },
      {"authorize", "50" }
   };

   std::vector<int> result;
   const long int M = pow(10, 9) + 7;
   long int value{ 0 }, strValue{ 0 }; // default initialization
   for (const std::vector<std::string> row: events) // better use range-based loop
   {
      strValue = std::stoi(row[1]);
      if (row[0] == "setpassword") {
         value = hashingfunct(row[1], M);

         if (strValue == value)
            result.emplace_back(1);
         else if (authorize(strValue, value, M))
            result.emplace_back(1);
      }
      else
         result.emplace_back(0);
   }
}

В качестве примечания:

0 голосов
/ 21 июня 2020

Corrected code

#include<bits/stdc++.h>
using namespace std;
bool authorize(long int strValue,long int value,int M){
    long int value1=value*131;
    long int newValue=(strValue-(value1%M))%M;
    if(newValue>=48 && newValue<=57)
    return true;
    if(newValue>=65 && newValue<=90)
    return true;
    if(newValue>=97 && newValue<=122)
    return true;
 return false;
}
int hashingfunct(string str,int M){
    long int P,F,sum=0;
    int len=str.length();
    for(int i=0;i<len;i++){
        P=pow(131,len-i-1);
        F=(int)str[i];
        sum+=(F*P)%M;
    }
    sum=sum%M;
    return sum;
}
int main(){
    int n=5;
    string str1,str2;
    vector<vector<string> > events;
    for (int i=0;i<n;i++){
        cin>>str1>>str2;
        vector<string > temp;
        temp.push_back(str1);
        temp.push_back(str2);
        events.push_back(temp);
    }

/*
setPassword cAr1
authorize 223691457
authorize 303580761
setPassword d
authorize 100
*/
    vector<int> result;
    int j=0;
    long int m=pow(10,9);
    long int M=m+7;
    long int value,strValue;
    for(int i=0;i<events.size();i++){
        
        if(events[i][0]=="setPassword"){
            value=hashingfunct(events[i][1],M);
            continue;
        }
        strValue=stoi(events[i][1]);
        if(strValue==value)
        result.push_back(1);
        else if(authorize(strValue,value,M))
        result.push_back(1);
        else
        result.push_back(0);
        
    }
    

    for(int i=0;i<result.size();i++){
        cout<<result[i];
    }


}
...