首页 > 解决方案 > 如何在 C++ 中将 std::string::const_iterator 类型转换为 int 类型

问题描述

我是 C++ 的新手

我想用c++实现字符串拆分功能,所以写了如下代码:

#include <vector>
#include <regex>
#include <sstream>
#include <string>

    std::string str = "1:2-3:4";
    std::smatch result;
    std::regex pattern("[:-]");

    std::string::const_iterator iterStart = str.begin();
    std::string::const_iterator iterEnd = str.end();


    std::vector<std::string> splitList = {};
    while (regex_search(iterStart, iterEnd, result, pattern))
    {
        // If std::string::const_iterator provides the int attribute
        // splitList.push_back(str.substr(iterStart.int, result[0].first.int));

        iterStart = result[0].second;
    }

的类型result[0].firststd::string::const_iterator,而str.substr函数需要type的参数int,所以我想转换result[0].firstintTypes of

感谢帮助。

标签: c++

解决方案


XY 问题。你不想要一个 int 类型,你想要那个子字符串,你可以通过你拥有的迭代器来获得它。像这样:

splitList.emplace_back( iterStart, result[0].first );

推荐阅读