我可以在循环中将std :: string的一部分引用到外部吗?

问题描述 投票:0回答:2

我在一个函数中解析一个std :: string,它将字符串作为const std::string&参数,对我来说,在遇到空格后取出其余的字符串是很有用的。我想在该阶段存储对字符串尾部的引用,并使用它来避免复制字符串。

我在for循环中有一个switch语句迭代字符串,我需要在其中一个case标签中获取ref。问题是您无法重新分配给参考AFAIK,并且在案例中声明引用也是非法的。此外,我也需要在开关外部使用ref。

这是一个简化的例子:

#include <string>

bool isValid(const std::string &s)
{
    unsigned int length {s.length()};
    for (unsigned int i {0}; i < length; ++i)
    {
        switch s[i]
        {
            // whatever other cases
            case ' ':
                const std::string &tail {s.substr(i, length - i};
                break;
            default:
                // whatever
        }
        if (tail == "abcd")
            // do something
    }
}

我不确切知道应该发生什么,因为我几乎是一个C ++新手,但我只是想在不使用ref的情况下节省堆上复制和分配的成本。

c++
2个回答
0
投票

我想在该阶段存储对字符串尾部的引用,并使用它来避免复制字符串。

引用是对象的别名,因此不存在对std::string对象的一部分的引用。您可以创建一个新的子字符串,例如与std::string::substr发布时:

const std::string &tail {s.substr(i, length - i};

请注意,这是有效的,因为const限定引用延长了临时的生命周期,这里是s.substr(...)的返回值,但很奇怪。

一个更干净的方法是首先传递std::string_view,这是为这种用例精确定制的,并使用std::string_view::substr提取部分字符串的新视图。这样效率更高(因为不必复制缓冲区)和惯用语。

#include <string_view>

bool isValid(const std::string_view &s)
{
    // ...

    const std::string_View tail = s.substr(i, length - i);

}

2
投票

我想存储对字符串尾部的引用

std::string &是对字符串的引用。它不是对字符串的一部分的引用。

这就是std::string_view的用途:

const std::string_view tail =
    std::string_view(s).substr(i, std::string_view::npos);

在C ++ 17之前,您可以简单地使用一对迭代器:

auto substr_beg = s.begin() + i;
auto substr_end = s.end();
© www.soinside.com 2019 - 2024. All rights reserved.