C++ substring on pointers
c++, memory, performance, string
Solution
Yes, it's possible.
You should write your own class as a wrapper around beginning and ending of the sub-string.
This code is not complete, but show the direction.
class string_ref
{
std::string::iterator b, e; // begin and end
public:
string_ref(std::string::iterator b, std::string::iterator e) : b(b), e(e){}
std::string to_string() const {
return std::string(b, e);
}
std::string::iterator begin() const {
return b;
}
std::string::iterator end() const {
return e;
}
// ... Code to complete this class ... //
};
std::ostream &operator<<(std::ostream &out, const string_ref &str) {
// out << str.to_string();
for (std::string::iterator i = str.begin(); i != str.end(); i++) cout << *i;
return out;
}
int main() {
std::string s = "Hello";
string_ref sr(s.begin(), next(s.begin(),3)); // pick first 3 charaters
cout << sr << endl; // print it by cout
}
You can iterate and print it simply.
Problem
Is it possible in C++ to create a substring as pointers to the same memory as the original string? Lets say I've got a string `s = "just testing"` and a function `f`. I want function f to return a constant string object (user can not change it), which will be a substring of `s` and I want `f` to create this substring the most efficient way. The only idea I've got is to return a pair of pointers - on the beginning and end of the substring, but I would love to give the end user the "feeling" that `f` returns an object and he can print it, iterate over it etc. Is it possible in C++?