【发布时间】:2013-12-08 00:56:25
【问题描述】:
如果我有一个包含另一个类的向量的类,并且我希望它很长:
class NucleotideSequence{
private:
std::string Name;
std::vector<Nucleotide> Sequence;
public:
NucleotideSequence();
NucleotideSequence(std::string name, std::vector<Nucleotide> seq);
std::string getName();
Nucleotide* getBase(int pos1);
int getLength();
void print();
};
在这种情况下是向量序列,我是否需要通过在构造函数中创建序列 *Sequence 并创建一个新向量来动态分配它?我想确保为大型向量(超过数十万个元素)使用正确的资源(堆栈与堆)。哪个是正确的做法?我听说向量包装了动态数组分配。
编辑:
我在下面提供了更新的代码,以表明我已经为构造函数使用了引用传递。我也希望使用移动构造函数,这样我就可以在一个函数中创建这些对象,然后将它们移到外面。
还给出了更新的 getPos 方法,如果该位置在序列中不存在,则会引发错误。
class NucleotideSequence{
private:
std::string Name;
std::vector<Nucleotide> Sequence;
public:
NucleotideSequence();
NucleotideSequence(const std::string &name, const std::vector<Nucleotide> &seq); // Note that a pointer is not needed since the std::vector class allocated memory on the heap for us and is a wrapper for that whole RAII process.
std::string getName();
Nucleotide getBase(int pos);
int getLength();
void print();
};
NucleotideSequence::NucleotideSequence(const std::string &name, const std::vector<Nucleotide> &seq)
{
Name = name;
Sequence = seq;
}
// Get a specific base
Nucleotide NucleotideSequence::getBase(int pos)
{
for(std::vector<Nucleotide>::iterator i = Sequence.begin(); i != Sequence.end(); i++)
{
if(pos == i->getPos())
{
return *i; // Return the correct nucleotide object.
}
}
throw BoundsError(); // If the desired position is not found, throw the error.
}
谢谢, 本。
【问题讨论】:
标签: c++ class vector dynamic-memory-allocation