1

ベクトルを含むクラスがあります:

class Foo {
  typdef std::vector<int> Vec;
  Vec m_kids;
  void addKids(Vec::const_iterator begin, 
               Vec::const_iterator end) {
    m_kids.insert(m_kids.end(), begin, end);
  }
};

次の簡潔な関数呼び出しを許可する方法はありますか? addKids(上記の関数を変更することでしょうか?)

int main() {
  Foo foo;
  foo.addKids(23,51,681);             // these...
  foo.addKids(3,6,1,4,88,2,4,-2,101); // ...would be nice?!
}

C++0x ベクトル初期化子リストでできると思いますか? 残念ながら C++0x は使えません。ただし、それが役立つ場合は Boost を使用できます。

4

4 に答える 4

5

あなたはこれを行うことができます:

Foo foo;
foo << 3, 6, 1, 4, 88, 2, 4, -2, 101; //inserts all!

そのためには、次のように<<and,演算子をオーバーロードする必要があります。

class Foo {
  typdef std::vector<int> Vec;
  Vec m_kids;
public:
  Foo& operator<<(int item) {
    m_kids.push_back(item); return *this;
  }
  Foo& operator,(int item) {
    m_kids.push_back(item); return *this;
  }
};

これを実装したら、次のように書くこともできます。

foo << 3 << 6 << 1 << 4 << 88 << 2 << 4 << -2 << 101; //inserts all!

これでも、

foo, 3, 6, 1, 4, 88, 2, 4, -2, 101; //inserts all!

または、次のように両方を混ぜます。

foo << 3, 6, 1 << 4, 88, 2 << 4 << -2, 101; //inserts all!

//and this too!
foo,3 << 6, 1 << 4, 88, 2 << 4 << -2, 101; //inserts all!

すべて同じです!

しかし、ミキシングはうまくいきません。私の好みは最初のものです!

于 2011-08-26T06:50:33.517 に答える
1

100% 同じ構文ではありませんが、boost の list_of を確認してください: http://www.boost.org/doc/libs/1_47_0/libs/assign/doc/index.html#list_of

于 2011-08-26T06:41:23.970 に答える
0

これを行うブースト機能については知りません(おそらく、まだ見たことがないという理由だけで、「ブーストがそれを持っている」はほとんど公理です...)が、それを行う可変引数関数を定義できます。次のようになります。

void addKids(int N, ...) {
    va_list args;
    va_start(args, N);
    for(int i = 0; i < N; ++i) {
        int val = va_arg(args, int);
        m_kids.push_back(val);
    }
    va_end(args);
}
于 2011-08-26T06:42:17.217 に答える
0

イテレータの型を変更した場合

template<typename T>
void addKids(T begin, T end)
{
  m_kids.insert(m_kids.end(), begin, end);
}

次に、少なくともこれを行うことができます:

int kids={1,2,3,4};
foo.addKids(kids,kids+4);

これはかなり簡潔に思えます。

于 2011-08-26T06:56:59.083 に答える