【发布时间】:2021-12-01 10:53:05
【问题描述】:
编辑: 这与我对答案here的兴趣不谋而合:
目前,我一直在使用它,但是如果需要找到 str3、str4、....,这显然是有问题的。
size_t find(const std::string& line, const std::string& str1, const std::string& str2, int pos) {
int eol1 = line.find(str1,pos);
int eol2 = line.find(str2,pos);
return (eol1 < eol2) ? eol2 : eol1;
}
size_t find(const std::string& line, std::vector<std::string> vect, int pos ) {
int eol1;
eol1 = 0;
for (std::vector<std::string>::iterator iter = vect.begin(); iter != vect.end(); ++iter){
//std::cout << *iter << std::endl;
int eol2 = line.find(*iter, pos);
if (eol1 == 0 && eol2 > 0)
eol1 = eol2;
else if ( eol2 > 0 && eol2 < eol1)
eol1 = eol2;
}
return eol1;
}
问题: 为什么 std::begin() 不能用于静态而不能用于动态,什么是最简单或最有效的替代方案?
奇怪的是,我经常在 Fortran 例程中使用两三个词搜索,但在 c++ 社区中没有一个紧凑的“多字符串搜索”功能。如果您需要此功能,是否必须实现复杂的“grep”系列或“regex”?
bool contains(const std::string& input, const std::string keywords[]){//cannot work
//std::string keywords[] = {"white","black","green"}; // can work
return std::any_of(std::begin(keywords), std::end(keywords),
[&](const std::string& str) {return input.find(str) != std::string::npos; });
}
为什么矢量化版本也不能工作?
bool contains(const std::string& input, const std::vector<std::string> keywords){
// do not forget to make the array static!
//std::string keywords[] = {"white","black","green"};
return std::any_of(std::begin(keywords), std::end(keywords),
[&](const std::string& str) {return input.find(str) != std::string::npos; });
}
附加: 在学习“参数包”的路上,但还是有问题……
//base
size_t fin(const std::string& line, const std::string& str1) {
std::cout << var1 << std::endl;
return line.find(str1);
}
//vargin
template <typename... Types>
size_t fin(const std::string& line, const Types... var1) {
return fin(line, var1...);
}
【问题讨论】:
-
当您说“静态”和“动态”时,我假设您的意思是普通数组(用于“静态”)和指针(用于“动态”),对吗?然后考虑指针指向的内容:它只指向一个对象,并且语言中没有内置知识表明该单个对象后面可能有更多数据。当你(和你的程序)知道有更多对象时,系统如何知道它们何时结束?
-
请花些时间刷新the help pages,尤其是"What topics can I ask about here?" 和"What types of questions should I avoid asking?"。也可以通过tour 阅读How to Ask 好问题和this question checklist。请每个问题一个问题。
-
const std::string keywords[]不是静态的 或 动态的 - 它只是一个函数参数经历数组衰减到一个指针。如果您不希望原始数组表现得像原始数组一样,只需传递std::vector、std::array或数组引用即可。 -
顺便说一句,如果术语“矢量化”是指使用
std::vector,那么这不是正确的术语。向量化是如何并行使用多个值进行计算。 -
另外,作为参数
const std::string keywords[]被解析为const std::string* keywords。它不是一个数组,只是一个指针。
标签: c++