【问题标题】:Function returning iterators to construct STL containers函数返回迭代器以构造 STL 容器
【发布时间】:2021-12-09 10:44:07
【问题描述】:

我的任务是编写一个函数,该函数对字符串执行某种标记化操作,并返回一个开始和结束可迭代对象,可用于通过调用代码构造任何 STL 容器。如何在 C++ 中实现这一点?任何线索/想法表示赞赏。

【问题讨论】:

    标签: c++ c++11 stl c++14


    【解决方案1】:

    在 C++14 中,为了可用作 STL 容器的数据源,迭代器必须满足 LegacyInputIterator 命名要求。

    换句话说,它必须是一个结构或类,具有该规范所需的所有成员。

    一旦你构建了这样一个类型,那么只需创建一个函数来创建其中的两个:一个引用第一个元素,另一个引用最后一个元素的“过去”。

    最后你会得到大致这样的结果:

    #include <iostream>
    #include <iterator>
    #include <string>
    #include <vector>
    
    struct MyInputIterator {
      // Announce that this is an input iterator
      using iterator_category = std::input_iterator_tag; 
      
      // Announce the type of elements being iterated over.
      using value_type = std::string;
    
      // For the sake of this use-case, these three can be 
      // treated as "unfortunately necessary". 
      using difference_type = std::ptrdiff_t;
      using reference = value_type&;
      using pointer = value_type*;
    
      // You mostly just have to implement the three following methods.
      bool operator!=(const MyInputIterator&) const;
      MyInputIterator& operator++();
      value_type operator*() const; 
    
      // N.B. For a pure input iterator, having operator*() return by value is 
      // often preferable, but returning by reference is required for other iterator
      // categories.
    };
    
    std::pair<MyInputIterator, MyInputIterator> tokenize(const std::string&);
    
    int main() {
      auto tok_ite_pair = tokenize("hi there");
    
      std::vector<std::string> tokens(result.first, result.second); 
    }
    
    

    【讨论】:

    • 这解释了很多。让我玩弄,看看我能不能达到我想要的。我原以为这种事情会更常见。谢谢
    • @user1408865 公平地说,在 C++20 中,实现 std::input_iterator 概念更加简洁明了。但是对于 C++14,你必须使用这种机制,它可以追溯到 c++98
    猜你喜欢
    • 1970-01-01
    • 2012-12-24
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2010-12-19
    • 1970-01-01
    • 2011-12-25
    相关资源
    最近更新 更多