Nav*_*eth -2 c++ visual-studio-2013
该代码是在VS社区2013中编写的.该程序在调试器模式下运行良好.但执行时坠毁了.请让我知道可能是什么问题.样本测试案例:10 aaa bbb ccc aaa
该程序在第3个输入行崩溃,有时在第4个输入行.
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
class registeration
{
public:
char* name;
int count;
registeration *next;
registeration()
{
name = new char(20);
count = 0;
next = NULL;
}
};
int main()
{
int n;
cin >> n;
char* str = new char(n);
registeration *regStart = new registeration();
while (n--)
{
cin >> str;
if (regStart->next == NULL)
{
registeration *reg = new registeration();
regStart->next = reg;
reg->count++;
//strcpy(reg->name, str);
strcpy_s(reg->name, 20, str);
}
else
{
registeration *reg = new registeration();
reg = regStart->next;
while (reg->next != NULL && strcmp(str, reg->name))
{
//registeration *reg1 = new registeration();
reg = reg->next;
}
if (!strcmp(str, reg->name))
reg->count++;
else
{
registeration *reg1 = new registeration();
strcpy_s(reg1->name, 20, str);
reg1->count++;
reg->next = reg1;
}
}
}
registeration *reg = new registeration();
reg = regStart->next;
while (reg != NULL)
{
if (reg->count > 1)
cout << reg->name << endl;
reg = reg->next;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这些行中有一个明显的错误:
name = new char(20);
char* str = new char(n);
Run Code Online (Sandbox Code Playgroud)
它们分配一个初始化为给定值的单个字符.相反,您打算分配一个字符数组,您可以按如下方式进行操作:
name = new char[20];
char* str = new char[n];
Run Code Online (Sandbox Code Playgroud)
(用括号代替括号.)
最好使用标准C++实用程序为您管理内存,例如std::string字符串和/ std::vector或std::list容器.
编辑:此代码与您的代码完全相同,更好:
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
int n;
cin >> n;
map<string, int> m;
for(int i = 0; i < n; ++i)
{
string s;
cin >> s;
m[s]++;
}
for(const auto &pr : m)
if(pr.second > 1)
cout << pr.first << '\n';
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37 次 |
| 最近记录: |