我的问题与下面的线程相同,我很难理解给出的答案,或者说我的代码不应该工作,因为它只使用输入迭代器..但我的func似乎工作和行为与std :: search相同. .所以我很茫然,不愿意继续前进而不理解......也许如果有人可以提出一个会破坏我的功能而不是std的输入::
从我为什么需要Forward Iterator来实现我自定义的std :: search:
我正在研究Koenig&Moo的"Accelerated C++"一书.
练习8-2让我自己实现一些来自<algorithm>和<numeric>的模板化函数,并指定我的实现需要什么样的迭代器.
在尝试实现std :: search时,我确定我只需要"输入"迭代器.
但是,看看用我的编译器安装的std :: search的实现,我可以看到它们使用"前向"迭代器,但我无法理解为什么,因为没有必要编写,只能读取,输入迭代器符合需求.
请问有人帮我理解这个吗?为什么我需要使用"前向"迭代器来实现std :: search?
提前致谢.
MyFunction的:
template <class In>
In search( In begin, In end, In begin2, In end2 )
{
In found ; // iter: 1st element in pattern match(in content)
In pattern_begin = begin2 ; // iter: 1st element in search pattern.
int flag = 0 ; // flag: partial match found?
// search content for pattern
while ( begin …Run Code Online (Sandbox Code Playgroud) 我已经阅读了各种描述,std::string::c_str包括多年来/几十年来提出的问题,
我清楚地喜欢这个描述:
返回指向数组的指针,该数组包含表示字符串对象当前值的以空字符结尾的字符序列(即C字符串).此数组包含组成字符串对象值的相同字符序列以及末尾的附加终止空字符('\ 0').
然而,关于此功能目的的一些事情仍然不清楚.
你可以原谅认为调用c_str可能会\0在字符串的末尾添加一个字符,该字符存储在host对象的内部char数组中(std::string):
s[s.size+1] = '\0'
Run Code Online (Sandbox Code Playgroud)
但是,std::string即使在调用之前,默认情况下对象仍然是Null终止c_str:

看完定义后:
const _Elem *c_str() const _NOEXCEPT
{ // return pointer to null-terminated nonmutable array
return (this->_Myptr());
}
Run Code Online (Sandbox Code Playgroud)
我没有看到任何代码会添加\0到char数组的末尾.据我所知,c_str只返回一个指向存储在数组的第一个元素中的char的指针begin().我甚至没有看到检查内部数组被终止的代码\0
或者我错过了什么?
将函数作为另一个函数的参数传递时遇到一些麻烦......
错误:错误1错误C2664:'wrapper':无法将参数1从'int'转换为'int(__ cdecl*)(int)'
int inc( int n )
{
return n + 1 ;
}
int dec( int n )
{
return n - 1 ;
}
int wrapper( int i, int func(int) )
{
return func( i ) ;
}
int main(){
int a = 0 ;
a = wrapper( 3, inc( 3 ) ) ;
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)