程序中的C ++ vector std :: bad_alloc错误

时间:2017-06-08 05:44:52

标签: c++ bad-alloc

我试图在一个基础上对具有两个值的用户定义数据类型的向量进行排序。但我得到bad_alloc的错误。这是代码:

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

using namespace std;

struct s{
int value;
int weight;
};

bool comp(s a , s b){
return a.value>b.value;
}

int main(){
vector <s> p;
s temp;
int n;
cin>>n;
while(n>=1){
    cin>>temp.value;
    cin>>temp.weight;
    p.push_back(temp);
}
sort(p.begin(), p.end(), comp);
vector <s> :: iterator it;
for(it = p.begin(); it != p.end();it++){
    *it = temp;
    cout<<temp.value<<endl;
}

}

正在运行:

  

在抛出&#39; std :: bad_alloc&#39;的实例后终止调用     what():std :: bad_alloc

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

我看到的问题:

无限循环

在循环中

while ( n >= 1)
{
   ...
}

您没有更改n的值。如果n比循环开始时更大1,则循环将永远不会结束。

未检查输入状态

你有

 cin >> temp.value;
 cin >> temp.weight;

您没有检查这些调用是否成功。您假设他们已经并且继续使用temp

错误的分配方式

在最后一个循环中,您正在使用

*it = temp;

这将改变vector,而不是从矢量中提取值。

这是main的更新版本,应该有效。

int main()
{
   vector <s> p;
   s temp;
   int n;
   cin>>n;
   while(n>=1)
   {
      // If there is a problem reading, break.
      if ( !(cin>>temp.value) )
      {
         break;
      }

      // If there is a problem reading, break.
      if ( !(cin>>temp.weight) )
      {
         break;
      }

      p.push_back(temp);

      // Decrement n
      --n;
   }

   sort(p.begin(), p.end(), comp);
   vector <s> :: iterator it;
   for(it = p.begin(); it != p.end();it++)
   {
      // Extract the value from the vector and print it.
      temp = *it;
      cout<<temp.value<<endl;
   }
}

答案 1 :(得分:1)

如果用户为n输入值1或更高,则循环永远不会结束,填充向量直到它耗尽所有可用内存。在每次循环迭代中,您不会递减n,因此循环最终会中断:

while (n >= 1) {
    cin >> temp.value;
    cin >> temp.weight;
    p.push_back(temp);
    --n; // <-- add this
}

在这种情况下,for循环比while循环更合适:

for (int i = 0; i < n; ++i) {
    cin >> temp.value;
    cin >> temp.weight;
    p.push_back(temp);
}

通过为operator>>定义自定义struct s然后将std::copy_n()std::istream_iterator和{{1}一起使用,我会完全摆脱手动循环}:

std::back_inserter

无论如何填充向量,您的#include <iostream> #include <algorithm> #include <iterator> istream& operator>>(istream &in, s &out) { in >> out.value; in >> out.weight; return in; } int main() { ... int n; cin >> n; copy_n(istream_iterator<s>(cin), n, back_inserter(p)); ... } 函数都应该通过引用获取其输入参数:

comp

此外,您的输出循环未正确使用迭代器。您需要摆脱bool comp(s &a, s &b) { return a.value > b.value; } 赋值,并按原样输出引用的值:

*it =
相关问题