C ++:为什么我不能将一对迭代器传递给regex_search?

时间:2015-10-23 16:40:17

标签: c++

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

    #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))

2 个答案:

答案 0 :(得分:1)

您遇到的问题是传递给regex_search的迭代器和为smatch定义的迭代器之间的类型不匹配。 std::smatch定义为:

typedef match_results<string::const_iterator> smatch;

iterend的类型为

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;
}

Live Example

答案 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();

或使用cbegincend

auto iter = test.cbegin();
auto end = test.cend();