C ++:为什么我不能将一对迭代器传递给regex_search? [英] C++: Why I can't pass a pair of iterators to regex_search?

查看:59
本文介绍了C ++:为什么我不能将一对迭代器传递给regex_search?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试传递一对迭代器来表示一个字符串序列:

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(__ gnu_cxx :: __ normal_iterator>& ;, __gnu_cxx :: __ normal_iterator>& ;, std :: smatch& ;, std :: regex&)的匹配函数不匹配"if(regex_search(iter,end,results,r))

error: no matching function for call to ‘regex_search(__gnu_cxx::__normal_iterator >&, __gnu_cxx::__normal_iterator >&, std::smatch&, std::regex&)’ if(regex_search(iter,end,results,r))

推荐答案

您遇到的问题是传递给 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆