c++ - Simple insert-erase-insert on std::deque<char> gives strange result -
here simple program
#include <iostream> #include <deque> #include <string.h> std :: deque <char> d; int main () { const char * x = "abcdefg"; d .insert (d .end (), x, x + strlen (x)); d .erase (d .begin (), d .begin () + 4); d .insert (d .end (), x, x + strlen (x)); std :: cout .write (& d [0], d .size ()); }
i expected output "efgabcdefg", actual output, in hex, is
65 66 67 00 00 00 00 c9 0b 02
which "efg???????"
what has gone wrong?
the problem output deque
has no guarantee elements stored contiguously, , in fact not be. means when take address of first element , size may not accessing elements of deque
.
you have multiple approachs solve problem.
the simplest seems to use string
instead of deque
. printing becomes trivial, , cut-then-append trivial.
you use example ostream_iterator
print out contents of deque
.
finally use vector
instead is guranteed store elements contiguously.
Comments
Post a Comment