2

Maybe a noob question but why these two lines:

vector<char> v{"h","i"};
string s1(v.cbegin(), v.cend());

won't compile? It says:

"debug assertion failed, exception:transposed pointer range".

wohlstad
  • 12,661
  • 10
  • 26
  • 39
yemeth
  • 41
  • 5
  • 3
    The `{"hi","i"}` will be seen as `{char const* begin, char const* end}` due to pointer decay, but since the two strings are unrelated it is **undefined behavior** as to what happens — which means anything can happen, it may even appear to work as expected (if you are particularly unlucky). – Eljay Jun 07 '22 at 13:19
  • @Eljay turn this into answer. – Marek R Jun 07 '22 at 13:27

1 Answers1

4

Debug assetions happen in run-time, not compile time.
In any case, you should change:

vector<char> v{"h","i"};

to:

vector<char> v{ 'h','i' };

char literals should be enclosed with ', not ".
This way your code should compile and run properly.

See also @Eljay's comment above for more info how the compiler actually interpreted your current code.

Side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • Thanks! Btw I'm aware of the problem of using namespace std, but is there a convienient way to avoid it? Adding std:: everywhere, or write a lot of using std:: *** feels a bit time comsuming, especially when I'm doing excercises of C++ primer, where I need to write a lot of things belong to std. – yemeth Jun 07 '22 at 13:30
  • 1
    @yemeth despite the inconveniency, it's advised to avoid it. The link I posted contains good reasons. It's up yo you of course, but keep in mind if you'll use it a lot you might find it hard to break the [bad] habbit. – wohlstad Jun 07 '22 at 13:36
  • @ wohlstad done. Thanks again – yemeth Jun 09 '22 at 01:45