我昨天发了一个帖子,但我放弃了它,用c++代替Java。
我在安装在我电脑上的编译器上测试了代码,它运行得很好。当我在HackerRank上运行它时,它一直给我分段错误。请查看下面的代码和编译器输出。
我读了一些帖子,提到它可能发生由于非法内存访问,但我不知道我在哪里做了。我已经花了5个多小时了,一会儿我会回来的。如有任何帮助,不胜感激。
struct Date
{
int Day;
int Year;
int Month;
bool latest(Date d){
if (Year > d.Year){
return true;
}
else if (Year == d.Year)
{
if(Month > d.Month){
return true;
}
else if (Month == d.Month){
if(Day> d.Day){
return true;
}
}
}
}
};
Date ThirdLatest(std::vector<Date> &dates) {
vector<Date> d;
int length = dates.size();
//std::cout << std::unitbuf;
for (int i=0; i<length; i++){
int flag = 0;
for (int j=0; j<d.size(); j++){
if (dates[i].Day == d[j].Day && dates[i].Month == d[j].Month && dates[i].Year == d[j].Year){
flag = 1;
break;
}
}
if (flag ==1)
d.push_back(dates[i]);
}
Date temp;
for (int i=0; i<d.size(); i++){
for (int j=i+1; j<d.size(); j++){
if (!d[i].latest(d[j])){
temp.Day = d[i].Day;
temp.Month = d[i].Month;
temp.Year = d[i].Year;
d[i].Day = d[j].Day;
d[i].Month = d[j].Month;
d[i].Year = d[j].Year;
d[j].Day = temp.Day;
d[j].Month = temp.Month;
d[j].Year = temp.Year;
}
}
}
return d[2];
}
int main() {
int numberOfEntries;
int res = scanf("%dn", &numberOfEntries);
std::vector<Date> dates;
for (int i = 0; i < numberOfEntries; ++i)
{
Date date;
res = scanf("%d-%d-%d", &date.Day, &date.Month, &date.Year);
dates.push_back(date);
}
Date result = ThirdLatest(dates);
printf("%02d-%02d-%dn", result.Day, result.Month, result.Year);
return 0;
}
编译器输出
Reading symbols from Solution...done.
[New LWP 71078]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 ThirdLatest (dates=...) at Solution.cpp:57
57 for (int i=0; i<length; i++){
To enable execution of this file add
add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual. E.g., run from the shell:
info "(gdb)Auto-loading safe path"
样本输入:7
14-04-2001
29-12-2061
21-10-2019
07-01-1973
19-07-2014
11-03-1992
21-10-2019
期望产出:19-07-2014
错误在这里
if (flag ==1)
d.push_back(dates[i]);
应该是
if (flag == 0)
d.push_back(dates[i]);
你的逻辑错了。你试图避免向向量中添加重复项,但你最终只添加了重复项,这意味着没有任何东西被添加到d
向量中。然后这一行
return d[2];
导致非法访问错误。
加上这个函数缺少一个返回语句
bool latest(Date d){
if (Year > d.Year){
return true;
}
else if (Year == d.Year)
{
...
}
return false; // this line is necessary
}