Search code examples
c++stldeque

Simple insert-erase-insert on std::deque<char> gives strange result


Here is a 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 the output to be "efgabcdefg", the actual output, in hex, is

65 66 67 00  00 00 00 C9  0B 02

which is "efg???????"

What has gone wrong?


Solution

  • The problem with your output is that deque has no guarantee that its elements are stored contiguously, and in fact will almost certainly not be. This means that when you take the address of the first element and a size you may not be accessing all the elements of the deque.

    You have multiple approachs to solve your problem.

    The simplest seems to be to use string instead of deque. Then printing becomes trivial, and the cut-then-append is also trivial.

    You could also use for example an ostream_iterator to print out the contents of the deque.

    Finally you could use vector instead as it is guranteed to store its elements contiguously.