Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing a vector<int> with 2 string literals

For the following program:

#include <vector>
#include <iostream>

int main()
{
  std::vector<int> v = {"a", "b"};
  
  for(int i : v)
    std::cout << i << " ";   
}

clang prints 97 0. The ascii value of 'a' is 97, but I don't fully understand the output.

On the other hand, gcc throws an exception:

terminate called after throwing an instance of 'std::length_error'
  what():  cannot create std::vector larger than max_size()

so I assume it's using the 2 argument constructor that takes the size and default value, where the size is computed from the address of the string literal "a".

If the program is well-formed, what is the correct behavior? Here's the code.

like image 221
cigien Avatar asked Jul 10 '20 13:07

cigien


People also ask

Can we make a vector of strings?

Conclusion: Out of all the methods, Vector seems to be the best way for creating an array of Strings in C++.

What are the two types of string literals?

A string literal with the prefix L is a wide string literal. A string literal without the prefix L is an ordinary or narrow string literal. The type of narrow string literal is array of char . The type of a wide character string literal is array of wchar_t Both types have static storage duration.


1 Answers

I assume it's using the 2 argument constructor that takes the size and default value

No, it's using the constructor taking two input iterators. "a" and "b" could decay to pointer which is valid iterator. As the pointer (iterator) to const char, the dereferenced const char would be converted to int and added as the vector's element. Anyway the code has UB because "a" and "b" don't refer to valid range, "b" is not reachable from "a".

like image 168
songyuanyao Avatar answered Sep 19 '22 00:09

songyuanyao