2

given a string s of type std::string I build another string s2 like so

std::string(s.begin(), s.begin() + s.find(" "))

but the following constructor doesn't work

std::string(s.begin(), s.find(" "))

anyone knows why ? I'm using g++ 4.8.1 under Ubuntu amd64

Both constructors have an iterator as second argument.

In this example I'm trying to build a string containing the first sub-string that ends where the first whitespace appears.

3 Answers 3

2

std::string::find() returns an offset, not an iterator (yes, it's largely a design inconsistency of the standard library). So to use this (and include proper error checking), do something like this:

size_t offset = s.find(" ");
std::string(s.begin(), (offset == std::string::npos ? s.end() : s.begin() + offset);
Sign up to request clarification or add additional context in comments.

6 Comments

oh, thanks, I don't know why I was really convinced to deal with an iterator, I assume that after dealing a lot with streams and chars you expect something like that ...
@user2485710: Perhaps you were thinking of the std::find() algorithm, which returns an iterator?
most likely, yes, but still can't understand why there is such approach for the string:: namespace. Anyway thanks.
@user2485710: I was never sure why the std::string type needed a ::find(), since there is a perfectly good free function, the fact that it has a different return type just adds to the confusion.
@Johnsyweb It seem Herb Sutter feels similarly.
|
1

Because find returns an index (size_type). Because a string is a contiguous container, s.begin() + s.find(" ") will return you an iterator, as it is equivalent to calling std::string::iterator operator+=(std::string::size_type s). The second one will of course be a compilation error.

3 Comments

is this the most efficient way of getting this kind of substring ?
Any way of getting the substring is going to be roughly the same performance: they're all going to be O(n), that is.
ok, I was thinking about a method that works by predicate and returns a copy of the substring matching that predicate, but I was expecting something like O(n). thanks.
1

Perhaps you were thinking of the std::find() algorithm, which returns an iterator?

#include <iostream>
#include <algorithm>

int main()
{
    std::string s = "Derek Smalls";
    std::string s2(std::begin(s), std::find(std::begin(s), std::end(s), ' '));
    std::cout << s2 << std::endl;
}

See it run!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.