我试图对具有用户定义数据类型的向量进行排序,该向量具有两个值,基于一个值。但是我得到了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;
}
}
跑步时:
在抛出"std::bad_alloc"实例后终止调用 什么(): 标准::bad_alloc
谁能帮忙?
我看到的问题:
无限循环
在循环中
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 或更高n
,循环永远不会结束,填充向量,直到它用完所有可用内存。您不会在每次循环迭代时递减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);
}
我会通过为struct s
定义自定义operator>>
来完全摆脱手动循环,然后将std::copy_n()
与std::istream_iterator
和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 =
赋值,只需按原样输出引用的值:
for(it = p.begin(); it != p.end(); ++it) {
//*it = temp; // <- get rid of this
cout << it->value << endl;
}