获取对字符串的子字符串的const访问
C++ - get const access to sub string of a string
假设我有一个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
(或者同样的begin
和end
和const 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());
}
相关文章:
- 为什么没有访问所有字符串字符?
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 循环访问还包含未使用元素的字符串数组
- 循环访问资源字符串表
- 在qt创建器中调试时如何访问字符串变量的完整值?
- 当我用"ñ"字符循环访问字符串时出现奇怪的结果
- 如何在读取文件时访问以前的字符串?
- C++字符串问题-如何访问字符串元素
- 访问包含P的有效索引时返回空格的C++字符串
- 交换两个字符串时访问正确的内存时,我遇到了分段错误
- C++/CLI访问字符串::来自非CLI代码的格式
- 需要从字符串数组的一部分访问元素
- 是否可以从字符串访问变量?
- 循环访问 c++ 中的字符串
- 循环访问字符串片段
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- 如何在 Qt/C++ 中仅将文件路径作为字符串访问文件
- C 使用字符串访问变量
- 基于字符串访问类成员
- 动态 C 字符串访问