从Python到C++的转换

vohkndzv  于 2022-11-26  发布在  Python
关注(0)|答案(1)|浏览(139)

我正在努力尝试把这个从python转换成c++,如果有人能帮忙的话,我将不胜感激。假设timern和Day变量已经给出,所以不需要time.ctime(thing)

if Day!=4:
    timeschedule=["08:30","09:20","10:10","11:00","11:30","12:20","13:10","14:00","14:45"]
else:
    timeschedule=["08:30","09:20","09:50","10:40","11:30"]
timern=time.ctime()[11:16]

for i in timeschedule:
    if timern<i:
        Finishes=i
        Period=timeschedule.index(Finishes)+1
        break
    else:
        continue

timern=timedelta(hours=int(timern[0:2]), minutes=int(timern[3:5]))
Finishes=timedelta(hours=int(Finishes[0:2]), minutes=int(Finishes[3:5]))

TimeLeft= Finishes-timern

seconds = TimeLeft.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
DayL=Days[Day]
Output=str(minutes)[0:2]+" minutes left till "+DayL[Period]

以下是我的转换尝试:

if (getCurrentDOWAsString=="Saturday" || getCurrentDOWAsString=="Sunday") {
  break;
}
else if (getCurrentDOWAsString=="Friday") {
  static const char *TimeSchedule[5] = {"08:30","09:20","09:50","10:40","11:30"};
}
else {
  static const char *TimeSchedule[9] = {"08:30","09:20","10:10","11:00","11:30","12:20","13:10","14:00","14:45"};
}

int Cn=0;
for (std::list<TimeSchedule>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
    int Cn=Cn+1;
    if (CTime < it) {
      char Finishes=it;
      int Period=Cn;
      break;    
}
int FinH = Finishes.substr(0,2);
int FinM = Finishes.substr(3,2);
if(FinM.minutes > minutes.minutes) {
  --hours.hours;
  minutes.inutes += 60;
}
  difference->minutes = minutes.minutes-FinM.minutes;
  difference->hours = hours.hours-FinH.hours;
  char TL = char(difference->hours)+":"+char(difference->minutes)

我总是在这里得到一个错误(std::list::iterator it = data.开始();如果您有一个数据库,那么您就可以使用它。it)特别是部分,我不知道为什么。这部分代码是从网上的一个简短教程中提取的,但我还没有完全掌握它的思想,这是我挣扎的地方。

2sbarzqh

2sbarzqh1#

只关注你所问的问题,一个可能的解决方案可能是(假设通过阅读代码片段,我们处于另一种循环中):

std::vector<std::string> data = {};
    
if (getCurrentDOWAsString=="Saturday" || getCurrentDOWAsString=="Sunday")
    break;
else if (getCurrentDOWAsString=="Saturday")
    data = {"08:30","09:20","09:50","10:40","11:30"};
else
    data = {"08:30","09:20","10:10","11:00","11:30","12:20","13:10","14:00","14:45"};
    
for (auto& hour : data)
    cout << "Hour: " << hour << std::endl;

总而言之:

  • 如果需要的容器没有固定大小,请使用std::vector
  • 在处理字符串时,几乎总是使用std::string。在现代C中尽量不要使用c-style类型
  • 通过使用这些集合,您可以使用ranged for loops,并摆脱了显式使用迭代器来以代码段中提供的方式迭代集合

相关问题