【发布时间】:2017-10-09 06:59:05
【问题描述】:
有没有办法使用标准库来简化与 strncmp 比较的结构数组上的循环?
以下是我失败的尝试,因为 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<_elem>) noexcept': 无法从 'nodeinput []
推导出 'std::initializer_list<_elem>' 的模板参数
【问题讨论】:
-
请提供准确的错误信息
-
首先,您要统计满足
strncmp(...) == 0的对象的数量,或者如果有这样的对象则返回1,否则返回0?ContainsObjectType做后者,但新版本尝试做前者。 -
考虑使用
std::string和它的方法而不是CString和c 字符串函数。您无需在每次使用struct类型时都指定struct。考虑使用标准容器而不是数组,这样做可以解决您的问题。 -
如果有一个该类型的对象,我想返回 1。错误是 C2784: 'const _Elem *std::begin(std::initializer_list<_elem>) noexcept': 无法从 'nodeinput []' 推断出 'std::initializer_list<_elem>' 的模板参数