【发布时间】:2018-01-22 10:08:45
【问题描述】:
我有一个列表向量。每个向量元素(在这种情况下是一个列表)在与向量索引相同的位位置存储具有 1(以二进制表示)的数字。即对于向量的第 5、第 0 和第 2 个元素(列表)将包含 5。但是程序在尝试将值插入列表的向量时终止。即使在调用reserve() 和resize() 之后,Vector 的容量仍然为0。如何正确执行此操作?请帮忙!以下是相关代码:
#include<iostream>
#include<algorithm>
#include<vector>
#include<list>
using namespace std;
void preprocess(int);
int test_case,x,y,monsters,queries;
int* health;
int to_change;
vector<list<int> > bits;
int main()
{
cin>>test_case;
while(test_case--)
{
cin>>monsters;
health = new int[monsters];
bits.resize(32);
bits.reserve(32);
for(int i=0;i<monsters;i++)
{
cin>>health[i];
preprocess(health[i]);
}
}
}
void preprocess(int val)
{
int a,this_bit,copy_of_health;
cout<<"currently:"<<val<<endl;
a=val,this_bit = 0,copy_of_health = a;
while(a)
{
if(a&1==1)
{
cout<<"Working on val"<<endl;
bits[this_bit].push_back(copy_of_health); //fails to execute this line
cout<<"done upto this"<<endl;
cout<<"This list size:"<<bits[this_bit].size()<<endl;
cout<<"pushed"<<copy_of_health<<"successfully"<<"in bit position"<<this_bit<<endl;
}
this_bit++;
a >>= 1;
}
}
【问题讨论】:
-
为什么要使用
int*并使用它在每次迭代时分配额外的内存。每次循环时,都会泄漏monsters * sizeof(int)字节。这使代码混乱,因为底层方法不正确,因此很难说出其意图。 -
在
resize之后调用reserve是没有意义的。更简洁的方法是使用push_back而不是resize+ 按索引赋值。 -
旁白:如果有人为您的怪物数量输入“x”;你会有一些糟糕的时光。
-
你为什么还要这个列表向量?如果您将目标写得更清楚,我们可能会提供比您想要实现的更好的解决方案。
-
是的,实际上我的代码存在一些严重问题。正如您所提到的,它存在内存泄漏(我忽略了它并感谢您的注意)、输入验证、全局变量问题。但我的问题是关于方法 preprocess() 未能将元素插入向量内的列表中。实际上没有使用列表的具体原因。也可以用向量内的向量来完成。正如我所写的,我想要做的是以这样的方式存储一些数字,即在相同位位置具有 1 的每个数字都属于同一组。因此,一个数字可以存储在多个组中。