问题描述
我尝试传递一对迭代器来表示一个字符串序列:
I try to pass a pair of iterators to represent a string sequence:
#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
的迭代器与为定义的迭代器之间的类型不匹配匹配
. std :: smatch
定义为:
The issue you are having here is a type mismatch between the iterators you are passing to regex_search
and the iterator defined for smatch
. std::smatch
is defined as:
typedef match_results<string::const_iterator> smatch;
和 iter
和 end
的类型为
string::iterator
调用迭代器版本 regex_search
时定义为
When you call regex_search
the iterator version is defined as
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
的迭代器和迭代器必须匹配.如果我们更改
And as we can see the iterators and the iterators of the match_result
have to match. If we change
auto iter = test.begin();
auto end = test.end();
收件人
auto iter = test.cbegin();
auto end = test.cend();
然后,所有内容现在都具有 string :: const_iterator
的类型,它将进行编译
Then everything now has the type of string::const_iterator
and it will compile
#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;
}
这篇关于C ++:为什么我不能将一对迭代器传递给regex_search?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!