替换循环以在数组上实现Contains

时间:2017-05-10 14:39:21

标签: c++ stl

有没有办法使用标准库来简化与strncmp比较的struct数组的循环?

下面是我的尝试失败,因为std :: count_if抱怨没有重载函数std :: begin匹配的实例。

#include "stdafx.h"
#include "afx.h"
#include <string.h>
#include <iostream>
#include <algorithm>
#include <string>

struct nodeobject
{
    CString ObjectType;
    nodeobject() {}
    explicit nodeobject(CString objectType) { ObjectType = objectType; }
};

struct nodeinput
{
    struct nodeobject Object;
};

// Original function I want to rewrite to remove the for loop and the strncmp
static int ContainsObjectType(int collectionSize, struct nodeinput collection[], char* objectType)
{
    auto found = 0;
    for (auto idx = 0; idx < collectionSize; idx++)
    {
        if (strncmp(objectType, 
                    collection[idx].Object.ObjectType, 
                    strlen(collection[idx].Object.ObjectType)) == 0)
        {
            found = 1;
        }
    }
    return found;
}

#if 0
// The implementation below does not compile because there is no instance of 
// overloaded function std::begin matches
static int ContainsObjectType(int collectionSize, struct nodeinput collection[], char* objectType)
{   
    auto numFound = std::count_if(std::begin(collection),
                                  std::end(collection),
                                  [](struct nodeinput oneNode) 
    { 
        return strncmp(objectType, oneNode.Object.ObjectType, oneNode.Object.ObjectType) == 0); 
    });

    return numFound > 0;
}
#endif

int main()
{
    struct nodeobject node1("fokker");
    struct nodeobject node2("airbus");
    struct nodeobject node3("boing777");
    struct nodeinput collection[] = {node1, node2, node3};
    auto nintnode = 3;

    auto found = ContainsObjectType(nintnode, collection, "boing777");

    std::cout << found << std::endl;
    return 0;
}

错误是:

  

C2784:const _Elem * std :: begin(std :: initializer_list&lt; _Elem&gt;)noexcept':无法推断'std :: initializer_list&lt; _Elem&gt;'的模板参数来自'nodeinput []

1 个答案:

答案 0 :(得分:2)

只需使collection成为指针,可能是const指针:

static int ContainsObjectType(int collectionSize, struct nodeinput *collection, char* objectType)
{   
    auto numFound = std::count_if(
        collection,
        collection + collectionSize,
        ...);
}

std::count_if的两个第一个参数必须是迭代器,而指针,实际上是原始迭代器。

std::begin(iterable)仅为pointerstd::end(iterable)pointer + <data length>