17

最小限のC++11 STLの例を考えると:

set<int> S = {1,2,3,4};
for(auto &x: S) {    
   cout << x;
   cout << ",";
}

x終了直前かどうかを確認する方法はありますか?この例の目標は1,2,3,4、最後のコンマではなく、出力することです。現在、2つのイテレータを持つ標準のforループを使用しています。

set<int>::const_iterator itr;
set<int>::const_iterator penultimate_end_itr = --S.end();
for(itr=S.begin(); itr!=penultimate_end_itr;++itr) 
    cout << (*itr) << ',';
cout << (*penultimate_end_itr);

これは機能しますが、ひどく面倒です。範囲ベースのforループ内でチェックを行う方法はありますか?

編集:質問のポイントは、コンマ区切りのリストを印刷しないことです。範囲ベースのforループに、リストの最後から2番目の要素(つまり、終了前の要素)に関する知識があるかどうかを知りたいです。最小限の例が提示されたので、私たち全員が話し合う共通のコードブロックを持っています。

4

2 に答える 2

19

範囲ベースのforループの目的は、イテレータを忘れることです。そのため、現在の値にのみアクセスでき、イテレータにはアクセスできません。次のコードはあなたのためにそれをしますか?

set<int> S = {1,2,3,4};

std::string output;
for(auto &x: S) {    
   if (!output.empty())
       output += ",";
    output += to_string(x);
  }

cout << output;

編集

別の解決策:イテレータを比較する代わりに(「通常の」forループで行うように)、値のアドレスを比較できます。

set<int> S = {1,2,3,4};
auto &last = *(--S.end());
for (auto &x : S)
{
    cout << x;
    if (&x != &last)
        cout << ",";
}
于 2012-08-30T15:28:36.763 に答える
7

Boost.Rangeはここで役立ちます:

if (std::begin(S) != std::end(S)) {
    std::cout << *std::begin(S);
    for (const auto &x: boost::make_iterator_range(std::next(std::begin(S)), std::end(S))) {
        std::cout << ", " << x;
    }
}

はるかに柔軟なアプローチは、boost::adaptors::indexed(Boost 1.56以降)を使用して範囲にインデックスを付けることです。

for (const auto &element: boost::adaptors::index(S)) {
    std::cout << (element.index() ? ", " : "") << element.value();
}

1.56より前のバージョンのBoostboost::adaptors::indexedでは機能しませんが、同様の機能を簡単に記述できます。

template <typename... T>
auto zip(const T&... ranges) -> boost::iterator_range<boost::zip_iterator<decltype(boost::make_tuple(std::begin(ranges)...))>>
{
    auto zip_begin = boost::make_zip_iterator(boost::make_tuple(std::begin(ranges)...));
    auto zip_end = boost::make_zip_iterator(boost::make_tuple(std::end(ranges)...));
    return boost::make_iterator_range(zip_begin, zip_end);
}

template<typename T>
auto enumerate(const T &range) -> boost::iterator_range<boost::zip_iterator<boost::tuple<
    boost::counting_iterator<decltype(boost::distance(range))>, decltype(std::begin(range))>>>
{
    return zip(boost::make_iterator_range(boost::make_counting_iterator(0),
        boost::make_counting_iterator(boost::distance(range))), range);
}

for (const auto &tup: enumerate(S)) {
    std::cout << (tup.get<0>() ? ", " : "") << tup.get<1>();
}

これは、c ++ 11のSequence-zip関数zipの関数を使用していますか?

于 2012-08-30T16:51:23.703 に答える