string conversion to vector<char>?

Feb 25, 2013 at 5:22pm
I need to create a function that turns a string into a vector of characters with each character holding a place in the vector. Anyone know how I can do this?
Feb 25, 2013 at 5:28pm
1
2
3
4
5
6
7
#include <string>
#include <vector>

std::vector<char> conv(const std::string &s)
{
    return std::vector<char>(s.begin(), s.end());
}


Not tested, but it should work.
Feb 25, 2013 at 5:29pm
Create a loop, that will loop the string.
vector.push_back( string[ index ] ) to the vector.
Feb 25, 2013 at 5:31pm
Thanks, are strings stored as sequences of chars in the computer's memory?
Feb 25, 2013 at 5:31pm
1
2
3
4
std::string s( "Hello" );
std::vector<char> v( s.begin(), s.end() );

for ( char c : v ) std::cout << c;

Feb 25, 2013 at 5:35pm
Thanks, are strings stored as sequences of chars in the computer's memory?

Hmm... in practice, yes.
But that's only been officially required since C++11, I believe?
Feb 25, 2013 at 5:42pm
@Catfish, your solution works fine! And thanks! lol. I love trying to help someone, but end up learning! (:
Feb 25, 2013 at 5:43pm
so...
s.begin()
and
s.end()
represent the first and last characters in the string?

and
std::vector<char> v( s.begin(), s.end() )
is creating the vector starting with the first character and ending with the last character?
Feb 25, 2013 at 5:45pm
> Thanks, are strings stored as sequences of chars in the computer's memory?

Stored as sequence of characters in the memory provided by the allocator.

That this sequence of chars must be stored contiguously was added in 2003.
Feb 25, 2013 at 5:56pm
so...
s.begin()
and
s.end()
represent the first and last characters in the string?


No.
s.end() - 1 is the iterator to the last character.
s.end() is the iterator to the imaginary character after the last character.

This is the convention, that the algorithms in the algorithm header follow for ranges: [ begin, end ) -- end is excluded.
This is the same for every other container, not just std::vector.
Feb 25, 2013 at 5:58pm
OK, that makes sense.
Thank you
Feb 27, 2013 at 5:16pm
Just an observation, why bother doing this when you can just use the string in the same manner as you would a vector. e.g.
s.push_back(); s[n]

Topic archived. No new replies allowed.