【问题标题】:how to make find() function using vector (class)如何使用向量(类)制作find()函数
【发布时间】:2018-12-07 12:18:05
【问题描述】:

有像as这样的类

class C_Service
{
public :

    C_Service(); {memset(this, 0, sizeof(*this));}
    C_Service(int type, int idx) {memset(this, 0, sizeof(*this));   this->type = type;  this->idx = idx;}
    bool operator==(const C_Service& svc) const { return (this->type == svc.type && this->idx == svc.idx);}

    word    type;
    word    idx;

    dword   aId;
    dword   bId;
    char*   name; 
};

我使用的测试代码如下,

void vec_find(int type, int idx)
{
    vector<C_Service*> vec;

    // added several items in vector vec
    ...

    vector<C_Service*>::iterator iter;
    C_Service cSvc(type, idx);
    iter = find(vec.begin(), vec.end(), &cSvc);
    C_Service* findsvc = *iter;
    if(findsvc)
        printf("FOUND : type(%d), idx(%d), name(%s)\n", findsvc->type, findsvc->idx, findsvc->name);
    else
        printf("Not FOUND!!\n");
}

然后,它给出“未找到!!”甚至设置正确的值。 我发现了一些错误并尝试更改..

iter = find(vec.begin(), vec.end(), &cSvc);

iter = find(vec.begin(), vec.end(), cSvc);

删除"&amp;" 然后它给出编译错误消息

/libcxx/algorithm: 在 '_InputIterator 的实例化中 std::__1::find(_InputIterator, _InputIterator, const _Tp&) [with _InputIterator = std::__1::__wrap_iter; _Tp = C_Service]':

'operator==' 不匹配(操作数类型为 'C_Service*' 和 'const C_Service')

我搜索到当我在Container中使用find()函数时,它可以使用operator== 但是,我无法达到目标..T.T

我的错是什么?

【问题讨论】:

  • vec的类型是什么?
  • 向量 vec;

标签: c++ algorithm vector find std


【解决方案1】:

问题在于您的 vec 是指针向量,而不是 C_Service 对象向量。

这样

find(vec.begin(), vec.end(), &cSvc)

检查cSvc 变量的地址是否包含在vec 中(这不是因为您刚刚创建了cSvc,因此无法从其他任何地方引用它)。它根本不使用您的operator==,它只是比较指针。

要修复它,您可以将 vec 更改为 std::vector&lt;C_Service&gt; 并执行

find(vec.begin(), vec.end(), cSvc)

或将自定义谓词传递给find_if,您可以在其中手动取消引用您的指针:

find_if(vec.begin(), vec.end(), [&](const C_Service *p) { return *p == cSvc; })

【讨论】:

  • 好吧,你简直比我快:)
  • @AndyLee 如果它解决了您的问题,请考虑接受此答案。
猜你喜欢
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 2021-05-21
  • 2019-08-12
  • 2016-11-27
  • 1970-01-01
相关资源
最近更新 更多