获取对字符串的子字符串的const访问

C++ - get const access to sub string of a string

本文关键字:字符串 访问 const 获取      更新时间:2023-10-16

假设我有一个Storage类:

class Storage
{
public:
  const string& get()                     const { return m_data;      }
  const char&   get(int ind)              const { return m_data[ind]; }
  const string& get(int s_ind, int e_ind) const { /* TBD */           }
private:
  string m_data; ///< Data is so big that part of it is stored on disk
}

假设我有一个Writer类,它获得const Storage&并需要访问其数据。
我的问题,有没有办法实现:

const string& get(int s_ind, int e_ind) const;

。e,只对string的一部分进行const访问。

指出:

get()被调用无数次,这是我的应用程序的瓶颈。我希望在访问数据时避免分配新对象。

有没有办法实现:

const string& get(int s_ind, int e_ind) const;

。E,只对字符串的一部分进行const访问。

绝对不会。

通常的做法是创建一个类来存储const char*size_t(或者同样的beginendconst char* s,或者迭代器,但是没有理由限制用于std::string s中的数据)。

然后你可以在string中创建一个"引用"文本的对象,并使用它,直到任何会使迭代器或对这些字符的引用无效的事件发生——参见标准或cppreference。可以支持stream输出,比较,索引等驱动的std::string托管数据。

显然,您无法将这样的类传递给硬编码std::string类型的函数,但您可以将其编写为具有类似的接口,这应该会减轻痛苦。

只是作为一个品尝者(没有看到编译器/在需要时充实)…

class Text_Ref
{
  public:
    Text_Ref(const char* p, size_t n) : p_(p), n_(n) { }
    // intuitive values for &text_ref[x] BUT text_ref[n] may not be nul
    const char& operator[](size_t o) const { return p_[n]; }
    *** OR ***
    // text_ref[n] is nul BUT can't use &text_ref[x]
    char operator[](size_t o) const { return o == n ? '' : p_[n]; }
    // same design trade off as the operator[] alternatives above
    char at(size_t o) const
    {
       if (o > n) throw std::out_of_range();
       return o == n ? '' : p_[n];
    }
    bool empty() const { return n == 0; }
    size_t size() const { return n; }
    size_t length() const { return n; }
    int compare(const char* p) const
    {
        do
        {
            if (*p != *p_)
                return (int)*p_ - *p;
        } while (*p);
        return 0;
    }
    bool operator< (const char* p) const { return compare(p) <  0; }
    bool operator<=(const char* p) const { return compare(p) <= 0; }
    bool operator==(const char* p) const { return compare(p) == 0; }
    bool operator!=(const char* p) const { return compare(p) != 0; }
    bool operator>=(const char* p) const { return compare(p) >= 0; }
    bool operator> (const char* p) const { return compare(p) >  0; }
  private:
    const char* p_;
    size_t n;
};
inline std::ostream& operator<<(std::ostream& os, const Text_Ref& t)
{
    return os.write(t.data(), t.size());
}