简体   繁体   English

C ++中模板拆分类构造函数的迭代器类型

[英]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 我希望能够传递我想要的任何迭代器: 例如:back_insterter(somevector),ostream_iterator

  • For back_inserter, what goes in Split < ?? 对于back_inserter,拆分<? > 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. 那些not_spacespace函数也应该是静态的,以使find_if起作用。 Or move them outside the class. 或将它们移到课堂之外。

One more thing: a back_insert_iterator does not need to be incremented. 还有一件事:back_insert_iterator不需要增加。 *destination = string(i,j); is enough. 足够。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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