简体   繁体   中英

iterator type for Template split class constructor in C++

template <class write_iter> //class for splitting a line into individual words
class Split
{
public:
split(const string& line, write_iter destination)
{
    typedef string::const_iterator iter;
    iter i;

    while(i != line.end())
    {
        i = find_if(i, line.end(), not_space);
        iter j = find_if(i, line.end(), space);

        if (i != line.end())
            *destination++ = string(i,j);

        i = j;
    }
}

bool not_space(char c)
{
    return !isspace(c);
}

bool space(char c)
{
    return isspace(c);
}
};

int main()
{
while(getline(cin, line))
    Split<> split(line, back_inserter(words));
}
  • I want to be able pass any sort of iterator i want: ex: back_insterter(somevector), ostream_iterator

  • For back_inserter, what goes in Split < ?? > split?

Split <decltype(back_inserter(words))>(line, back_inserter(words));

or here's the full type:

Split <std::back_insert_iterator<std::vector<std::string>>>(line, back_inserter(words));

Instead of having a templated class, why not just have a templated constructor? it would make things a lot easier.

Those not_space & space functions should be static as well for find_if to work. Or move them outside the class.

One more thing: a back_insert_iterator does not need to be incremented. *destination = string(i,j); is enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM