Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...