Reputation: 2293
I have a function that is expected to receive a list of individual characters through a const char *
. If I had to copy each character to a vector<char>
, what would be the best (i.e.: most efficient) way to perform the operation?
I have thought about copy
in algorithm, not sure if it's the more "elegant" solution:
void
example
(const char * const s)
{
copy(s, s+strlen(s), myvector.begin())
}
(hope that, given my "personal" indenting style, the code is still readable for you)
But I'm sure the STL implements something that allows me to copy until a null character is found in the string.
(If you wonder why I'm receiving a const char *
, well, that's the type the compiler creates when the user makes use of a temporal variable, and my function is expected to be called like example("fvh")
. Alternative solutions are welcomed)
Thanks in advance. Best regards, Kalrish
After trying what @ipc and @juanchopanza said, I feel stupid: it works like a charm.
Not still sure if I will lose performance, but, in any case, the compiler makes the implicit conversion, and it's pure C++, so it is definitely the way to go.
Thanks a lot, and sorry. Good luck, Kalrish
Upvotes: 1
Views: 931
Reputation: 275340
I am not aware of a copy until.
Here is a copy until '\0'
however:
#include <cstddef>
#include <algorithm>
#include <iostream>
#include <iterator>
struct str_copy_iterator {
bool at_end;
char const* ptr;
char operator*() const { return *ptr; }
typedef char value_type;
typedef std::ptrdiff_t difference_type;
typedef char* pointer;
typedef char& reference;
typedef std::output_iterator_tag iterator_category;
str_copy_iterator():at_end(true) {}
str_copy_iterator(char const* p):at_end(!p||!*p), ptr(p) {}
str_copy_iterator& operator++() {
++ptr;
at_end = !*ptr;
return *this;
}
str_copy_iterator operator++(int) {
str_copy_iterator tmp = *this;
++(*this);
return tmp;
}
bool operator!=( str_copy_iterator const& o ) const {
return !(*this == o);
}
bool operator==( str_copy_iterator const& o ) const {
if (at_end)
return o.at_end;
if (o.at_end)
return false;
return ptr == o.ptr;
}
};
int main() {
const char* bob = "hello world!";
char buff[100] = {};
std::copy(str_copy_iterator(bob), str_copy_iterator(), &buff[0] );
std::cout << buff << "\n";
}
extending the str_copy_iterator
into a generic iterator_until
wrapper is left as an exercise to the reader.
Upvotes: 2
Reputation: 227390
You can use an std::string
, and the std::vector::assign
method.
void example(const std::string& s)
{
myvector.assign(s.begin(), s.end()):
}
Upvotes: 0