【问题标题】:Find duplicate in templated vector [duplicate]在模板化向量中查找重复项 [重复]
【发布时间】:2015-08-24 14:23:36
【问题描述】:

我有一个模板class Timer

template<typename Clock, typename Duration>
class Timer
{
public:
    void Register(const std::function<void(const std::chrono::time_point<Clock> &timePoint)> &eventHandler);

private:
    std::vector<std::function<void(const std::chrono::time_point<Clock> &timePoint)>> eventHandlers;

// Some more stuff.
};

现在我想在Register 中找到重复的条目,这就是问题所在。
我使用std::find 和一个简单的for 循环尝试了不同的方法。

到目前为止我能做到的最好的(删除命名空间以提高可读性):

typename vector<function<void(const time_point<Clock> &timePoint)>>::iterator it;
for(it = eventHandlers.begin(); it != eventHandlers.end(); ++it)
{
}

我的问题是将Register的参数与it进行比较。
我尝试了几件事:

typename function<void(const time_point<Clock> &timePoint)> &f = &(*it);
if(f == eventHandler)
{
    // Duplicate
}

...以及其他一些更复杂的方法,但没有一个奏效。
我在解决这个问题时遇到了一些麻烦,因为我通常使用 C# 编写代码,因此我不习惯使用 C++ 进行模板化。
我该如何解决这个问题,还有更优雅的解决方案吗?

编辑:
我通常会收到此错误:

binary '==': no operator found which takes a left-hand operand of type 'std::function<void (const std::chrono::time_point<std::chrono::system_clock,std::chrono::system_clock::duration> &)>' (or there is no acceptable conversion)

【问题讨论】:

  • 这里的问题不在于模板,而在于std::functions 是not equality comparable。传递给Timer::Register 的两件事相等是什么意思?

标签: c++ templates


【解决方案1】:

注意:

typename function<void(const time_point<Clock> &timePoint)> &f = &(*it);
if(f == eventHandler)
{
    // Duplicate
}

我认为您的意思是输入typename function&lt;void(const time_point&lt;Clock&gt; &amp;timePoint)&gt; *f,因为&amp;(*it) 返回的是指针类型而不是引用。


更新

std::function== 不可比较,因此您可以执行以下操作:

不使用std::function,而是使用这样的函数指针(再次使用typedef):

typedef void(*name_of_type)(const time_point<Clock>&)>

然后将 name_of_type 替换为您想要的任何名称。

这样您就可以将operator== 与函数指针一起使用


更新 #2

我会通过把所有东西都放到你的课堂上来澄清这一切:

template<typename Clock, typename Duration>
class Timer
{
public:
    typedef void(*name_of_type)(const time_point<Clock>&)>

    void Register(name_of_type eventHandler);

private:
    std::vector<name_of_type> eventHandlers;
// Some more stuff.
};

使用 for 循环,您可以执行以下操作:

[非c++11]

typename vector<name_of_type>::iterator it;
for(it = eventHandlers.begin(); it != eventHandlers.end(); ++it)
{
//do what you want with *it
}

[c++11 以上]

for(auto& x: eventHandlers)
{
//do what you want with x
}

【讨论】:

  • 你回答的前半部分不回答问题,是多余的。它应该在您“更新”之后进行或被删除。
  • @NathanOliver - 我现在删除了它:)
猜你喜欢
  • 1970-01-01
  • 2018-10-13
  • 2016-01-18
  • 2013-02-21
  • 1970-01-01
  • 2021-12-11
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多