1

Here I have a 2d vector of char -

std::vector<std::vector<char>> solution = {
 {"O","1"}, 
 {"T","0"}, 
 {"W","9"}, 
 {"E","5"}, 
 {"N","4"}
};

Printing anything from first column - prints fine.

cout << "In main - " << solution [ 1 ] [ 0 ]; // Prints T

But when I try to access element of second column.

cout << "In main - " << solution [ 1 ] [ 1 ]; // Prints blank space - I can't seem to understand why's the case.

After quiet amount of searching I tried by putting single quotes around every element.

std::vector<std::vector<char>> solution = {
  {'O','1'}, 
  {'T','0'}, 
  {'W','9'}, 
  {'E','5'}, 
  {'N','4'}
};

It works fine in this case.

cout << "In main - " << solution [ 1 ] [ 1 ]; // Gives me 0 in this case.

Now why is it that I'm getting blank spaces when accessing second column in "" double quotes scene.

JeJo
  • 30,635
  • 6
  • 49
  • 88
tamir
  • 45
  • 6
  • 1
    Does this answer your question? [Constructing a vector with 2 string literals](https://stackoverflow.com/questions/62835713/constructing-a-vectorint-with-2-string-literals) TL;DR the first program has UB, so it might give any result. – cigien Jul 10 '20 at 14:28
  • I saw it somehow is related to my problem but doesn't explain or I didn't understood it. What's "TL:DR, UB"? I don't have range based loop, and second thing is it only happens with this string and one other string all other strings all working perfectly. Out of 10 test cases only 2 failed and they both have same problem printing either invalid character or spaces. – tamir Jul 11 '20 at 06:55
  • Sorry, TL;DR means "too long, didn't read". I've added an answer below that also explains UB. – cigien Jul 11 '20 at 15:04

1 Answers1

0

In your first example, for each element of solution, you are trying to construct a vector<char> from 2 string literals. This will use the constructor of vector that takes 2 iterators (since string literals can be converted to pointers). Since the pointers are not denoting a valid range, this invokes undefined behavior (UB).

In the second example, for each element of solution, you are trying to construct a vector<char> from 2 chars, which is perfectly fine, and gives you the result you expected.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • Anyway to tackle this? As input isn't really in my hand, and it will always be in string literals. – tamir Jul 12 '20 at 06:42