string conversion to vector<char>?

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?
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.
Create a loop, that will loop the string.
vector.push_back( string[ index ] ) to the vector.
Thanks, are strings stored as sequences of chars in the computer's memory?
1
2
3
4
std::string s( "Hello" );
std::vector<char> v( s.begin(), s.end() );

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

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?
@Catfish, your solution works fine! And thanks! lol. I love trying to help someone, but end up learning! (:
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?
> 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.
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.
OK, that makes sense.
Thank you
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.