【问题标题】:Input crash (C++)输入崩溃 (C++)
【发布时间】:2015-10-15 14:25:34
【问题描述】:

您好,我已经编写了代码,但是如果我想在输入代码后运行代码,它就会崩溃。 程序应该从向量中挑选出前 10 个,挑选最高的一个并销毁之前的所有内容并重新填充它,直到它再次长到 10 个。 我使用了一个 for 循环来做到这一点。我刚开始用这个像2个月。

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

using namespace std;
int main()
{
int Aantal;
cin >> Aantal;
vector<int> F(Aantal);
for(int i=0; i<Aantal; i++)
{
cin >> F[i];
    if(Aantal>1000)
    {
        cerr << "You're above 1000" << endl;
        return -1;
    }
    if(Aantal<20)
    {
        cerr << "You're below 20" << endl;
        return -1;
    }
    if(i>Aantal)
        {
            cerr << "Not above 'Aantal'" << endl;
            return -1;
        }
    if(i<0)
        {
            cerr << "Not smaller than 0!" << endl;
            return -1;
        }
}
for(int z=0; z<Aantal; z++)
{
if(z == 0){
    int a = 0;
}
int a;
vector<int> arr(F.begin()+a, F.begin()+10+a);
int c = *max_element(arr.begin(), arr.end());
cout << c << endl;
vector<int>::iterator q;
q = find(arr.begin(), arr.end(), c);
int pos = distance(arr.begin(), q);
arr.erase(arr.begin(),arr.begin()+pos);
int a1 = 10-arr.size();
int b = a+a1;
a = b;
if(a+10>Aantal)
    {
    break;
    }
arr.erase(arr.begin(), arr.end());

【问题讨论】:

  • 你能解释一下这里要做什么吗? for(int z=0; z&lt;Aantal; z++) { if(z == 0){ int a = 0; } int a; vector&lt;int&gt; arr(F.begin()+a, F.begin()+10+a);

标签: c++ input crash


【解决方案1】:

你的问题在这里:

int a;
vector<int> arr(F.begin()+a, F.begin()+10+a);

你创建了一个变量a,从不初始化它,然后你用它来构造向量。由于a 具有垃圾值,这将扰乱向量创建,因为您很可能会得到错误的位置。

在此之前我不确定你在做什么:

for(int z=0; z<Aantal; z++)
{
if(z == 0){
    int a = 0;
}

所有这一切都将a 设置为零,然后您丢弃a,因为它在 if 块中声明。

【讨论】:

  • 我想继续计数我应该怎么做?我需要删除和重新填充矢量的解决方案。
猜你喜欢
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-24
  • 2012-04-06
相关资源
最近更新 更多