我尝试传递一对迭代器来表示字符串序列:
#include<regex>
#include<string>
using namespace std;
int main(int argc,char *argv[])
{
smatch results;
string temp("abc");
string test("abc");
regex r(temp);
auto iter = test.begin();
auto end = test.end();
if(regex_search(iter,end,results,r))
cout<<results.str()<<endl;
return 0;
}
错误如下:
错误:没有匹配函数来调用'regex_search(__ gnu_cxx :: __ normal_iterator&gt;&amp;,__ gn_cxx :: __ normal_iterator&gt;&amp;,std :: smatch&amp;,std :: regex&amp;)' 如果(regex_search(ITER,结束,结果,R))
答案 0 :(得分:1)
您遇到的问题是传递给regex_search
的迭代器和为smatch
定义的迭代器之间的类型不匹配。 std::smatch
定义为:
typedef match_results<string::const_iterator> smatch;
且iter
和end
的类型为
string::iterator
当您调用regex_search
时,迭代器版本定义为
template< class BidirIt, class Alloc, class CharT, class Traits > bool regex_search( BidirIt first, BidirIt last, std::match_results<BidirIt,Alloc>& m, const std::basic_regex<CharT,Traits>& e, std::regex_constants::match_flag_type flags = std::regex_constants::match_default );
正如我们所看到的,match_result
的迭代器和迭代器必须匹配。如果我们改变
auto iter = test.begin();
auto end = test.end();
到
auto iter = test.cbegin();
auto end = test.cend();
然后现在一切都有string::const_iterator
的类型,它将编译
#include<regex>
#include<string>
#include <iostream>
using namespace std;
int main()
{
smatch results;
string temp("abc");
string test("abc");
regex r(temp);
auto iter = test.cbegin();
auto end = test.cend();
if (regex_search(iter, end, results, r))
cout << results.str() << endl;
return 0;
}
答案 1 :(得分:0)
regex_search
需要const_iterator
,但您传递的是std::string::iterator
。
制作字符串const
const string test("abc");
声明const_iterator
std::string::const_iterator iter = test.begin();
std::string::const_iterator end = test.end();
或使用cbegin
和cend
auto iter = test.cbegin();
auto end = test.cend();