草庐IT

c++ - 具有复杂值类型 : confusion with value_type and reference 的迭代器

coder 2024-02-24 原文

我想创建一个自定义迭代器包装器,例如 enumerate : 给定一对类型为 T 的迭代器, 它会返回一个类型为 std::pair<const int, T&> 的可迭代对象,其中该对的第一个元素将取值 0、1、2,依此类推。

我无法确定应该是什么 value_typereference我的迭代器。我想支持两种行为:

首先,引用底层序列的值:

for (auto& kv: enumerate(my_vec)) {
    kv.second = kv.first;
}

(类似于 std::iota );

其次,复制值:

std::vector<int> a{10, 20, 30};
auto copy = *enumerate(a).begin();
a[0] = 15;
std::cout << copy.first << " " << copy.second; // 0 10

我很困惑 Iterator::operator*() 的返回类型应该是什么.如果是std::pair<const int, T&>那么在第二个示例中,值将不会被复制。如果是std::pair<const int, T>那么在第一个示例中,不可能引用基础值。我应该做什么,应该是什么value_type , referencepointer这种迭代器的类型定义?

这是我尝试实现它的尝试。支持引用,不支持复制。

template<typename T>
struct Iterator {
    using TT = typename std::iterator_traits<T>::value_type;

    using value_type = std::pair<const int, TT>;
    using reference = std::pair<const int&, typename std::iterator_traits<T>::reference>;
    using pointer = value_type*;
    using iterator_category = std::forward_iterator_tag;
    using difference_type = std::ptrdiff_t;

    std::pair<int, T> it;
    Iterator(T iterator) : it(0, iterator) {}
    bool operator==(const Iterator& other) const { return it.second == other.it.second; }
    bool operator!=(const Iterator& other) const { return it.second != other.it.second; }
    reference operator*() { return { it.first, *it.second }; }
    Iterator& operator++() { ++it.first; ++it.second; return *this; }
};

附言我刚刚检查过,boost::adaptors::index 遇到同样的问题并且没有复制值。

最佳答案

这个问题和std::vector<bool>的问题类似,你想提供一个代理,它的行为就像一个引用,但也支持值语义。

但不同的是,所涉及的类型不受限制,涉及两个引用,并且会弹出各种毛羽。以下是部分实现,它说明了您遇到的一些问题

#include<iterator>
#include<functional>

template<typename F, typename S, bool defined = true>
struct sfinae_difference_type {};

template<typename F, typename S>
struct sfinae_difference_type<F, S, 
        std::is_same_v<typename std::iterator_traits<F>::difference_type, 
                       typename std::iterator_traits<S>::difference_type>>
{
    using difference_type = typename std::iterator_traits<F>::difference_type;
};

template<typename F, typename S>
class pair_iterator : sfinae_difference_type<F, S>
{
    using Fvalue_type = typename std::iterator_traits<F>::value_type;
    using Svalue_type = typename std::iterator_traits<S>::value_type;
    using Freference = typename std::iterator_traits<F>::reference;
    using Sreference = typename std::iterator_traits<S>::reference;

    F f;
    S s;

public:
    using value_type = std::pair<Fvalue_type, Svalue_type>;

    struct reference
    {
        Freference first;
        Sreference second;

        reference() = delete;
        reference(const reference& other) : first{other.first}, second{other.second} {} 
        reference& operator=(const reference& rhs)
        {
            first = rhs.first;
            second = rhs.second;
            return *this;
        }
        operator value_type() { return {f, s}; }

    private:
        reference(Freference f, Sreference s) : first{f}, second{s} {}
        friend pair_iterator;
    };

    struct pointer
    {
        // similar to reference
    };

    pair_iterator() = default;
    pair_iterator(const pair_iterator&) = default;
    pair_iterator(F f, S s) : f{f}, s{s} {}
    pair_iterator& operator++() { ++f; ++s; return *this; }
    reference operator*() { return {*f, *s}; }
    pointer operator->() { return {f.operator->(), s.operator->()}; }
    bool operator==(const pair_iterator& other)
    {
        return f == other.f && s == other.s;
    }
};

然后您将其用作

#include<vector>
#include<list>
#include<iostream>

int main()
{
    std::vector v{1, 2, 3, 4, 5};
    std::list l{6, 7, 8, 9, 10};
    pair_iterator begin{v.begin(), l.begin()}, end{v.end(), l.end()};
    for(; begin != end; ++begin)
        std::cout << begin->first << ' ' << begin->second << '\n';
}

Live

一些立即显而易见的问题:

  1. 实现很乏味。拥有 sfinae 友好的类型别名和适当的代理需要大量的样板。
  2. 代理的语义可能令人困惑。什么是复制/分配一个 reference另一个意思?什么是 auto is_this_a_copy = *it应该做什么?
  3. 平等是什么意思?两个内部迭代器是否必须相等才能相等?这打破了与结束迭代器的比较。

所有这些都必须敲定才能使其发挥作用,而且没有一个简单的答案。

关于c++ - 具有复杂值类型 : confusion with value_type and reference 的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49096829/

有关c++ - 具有复杂值类型 : confusion with value_type and reference 的迭代器的更多相关文章

  1. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  4. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  5. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  6. ruby - 为什么 Ruby 的 each 迭代器先执行? - 2

    我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试

  7. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

  8. ruby-on-rails - 在 Rails 开发环境中为 .ogv 文件设置 Mime 类型 - 2

    我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain

  9. ruby-on-rails - Rails 3.1 中具有相同形式的多个模型? - 2

    我正在使用Rails3.1并在一个论坛上工作。我有一个名为Topic的模型,每个模型都有许多Post。当用户创建新主题时,他们也应该创建第一个Post。但是,我不确定如何以相同的形式执行此操作。这是我的代码:classTopic:destroyaccepts_nested_attributes_for:postsvalidates_presence_of:titleendclassPost...但这似乎不起作用。有什么想法吗?谢谢! 最佳答案 @Pablo的回答似乎有你需要的一切。但更具体地说...首先改变你View中的这一行对此#

  10. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

随机推荐