5

このようなことをしたのはこれが初めてなので、これをどのように行う必要があるのか​​ 少しわかりません。いくつかの単純な値といくつかのゲッターを含む非常に単純なクラスがあります。

class Nucleotide{
    private:
        char Base;
        int Position;
        int Polymorphic;
    public:
        Nucleotide(char ch, int pos);
        int getPos();
        char getBase();
        int getPoly();
};

このクラスは、それらのベクトルを含む別のクラスに存在します。

class NucleotideSequence{
    private:
        std::string Name;
        std::vector<Nucleotide> Sequence;
    public:
        NucleotideSequence(std::string name, std::vector<Nucleotide> seq);
        std::string getName();
        Nucleotide getBase(int pos1);
};

getBase という 2 番目のクラスのメソッドが整数 (たとえば 1) を取り、ベクトル内の最初の Nucleotide オブジェクトを返すことができるようにしたいと考えています。私が書いたものは以下のとおりです。

Nucleotide NucleotideSequence::getBase(int pos1)
{
    for(std::vector<Nucleotide>::iterator i = Sequence.begin(); i != Sequence.end(); i++)
    {
        if(pos1 == (*i).getPos())
        {
            return i; // Return a pointer to the correct base.
        }
    }
}

戻り値の型として Nucleotide を取得しましたが、これをどのように変更する必要があるのか​​ 本当に疑問に思っていました. したがって、ポインター/参照を返したいと思います。ループでイテレータを使用しているので、イテレータの値を持つポインタを返すだけでよいですか? どうすればいいですか?関数で i を返しますが、i& を返す必要がありますか? 詳細については不明です-おそらくポインターを返す場合、戻り値の型は Nucleotide* またはおそらく Nucleotide& である必要があります。私はこれを熟考し、Cpp tuts を読みましたが、まだ正しい答えが少しわかりません。

ありがとう、ベン。

4

4 に答える 4

0

あなたの質問に関する限り、他の人が提案したように参照 (&) を返すことが解決策です。

コードを改善するために、次の変更を提案します。

operator[] を使用するか、std::vector にある at() を使用します。

したがって、次のように直接言うことができます。

シーケンス[pos1]を返します。または、Sequence.at(pos1); を返します。

于 2013-11-13T13:02:56.653 に答える
0

コードは、効率のために参照を使用することでメリットが得られます。メソッドのシグネチャは次のgetBaseようになります。

const Nucleotide& NucleotideSequence::getBase(int pos1)

コンストラクターの署名は次のNucleotideSequenceようになります。

NucleotideSequence(const std::string& name, const std::vector<Nucleotide>& seq);

そして、getNameこのような方法:

const std::string& getName();

(ただし、戻り値の最適化により、その重要性が低下する可能性があります。)

getBase の内容については、コードを次のように分解すると理解に役立つ場合があります。

const Nucleotide* NucleotideSequence::getBase(int pos1)
{
    for(std::vector<Nucleotide>::iterator i = Sequence.begin(); i != Sequence.end(); ++i)
    {
        Nucleotide& ref = *i; //Get a reference to the object this iterator points to
        if(pos1 == ref.getPos()) //compare its base to the argument
        {
            return &ref; // Return a pointer to the correct object.
        }
    }
    return NULL; //or null if we didn't find the object we wanted
}
于 2013-11-13T13:09:58.100 に答える