ジェネリックイテレータを受け入れる関数を宣言する 質問する

ジェネリックイテレータを受け入れる関数を宣言する 質問する

このコードでは、のような の任意dumpStrings()のコンテナを反復処理できるように変更することは可能ですか?stringlist<string>

#include <vector>
#include <string>
#include <ostream>
#include <iostream>

using namespace std;

void dumpStrings(vector<string>::iterator it, vector<string>::iterator end)
{
    while (it != end) {
        cout << *it++ << endl;
    }
}

int main()
{
    vector<string> strVector;
    strVector.push_back("Hello");
    strVector.push_back("World");

    dumpStrings(strVector.begin(), strVector.end());
    return 0;
}

ベストアンサー1

テンプレートを作成する

template<class iterator_type>
void dumpStrings(iterator_type it, iterator_type end)
{
    while (it != end) {
        cout << *(it++) << endl;
    }
}

このテンプレートは、コンテナ値の型の文字列への制限も削除します。it++ を括弧で囲む必要があることに注意してください。

おすすめ記事