构建一个向量< int>。具有2个字符串文字 [英] Constructing a vector<int> with 2 string literals

查看:102
本文介绍了构建一个向量< int>。具有2个字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下程序:

#include <vector>
#include <iostream>

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

clang prints 97 0 'a'的ascii值为97,但是我不完全理解输出。

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

另一方面,gcc引发异常:

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()

,因此我假设它使用的是2个参数构造函数,该构造函数采用大小和默认值,其中大小是根据字符串文字 a 的地址计算的。

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.

推荐答案


我假设它正在使用2个参数构造函数,该构造函数采用大小和默认值

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

不,使用构造器,并使用两个输入迭代器。 a b 可以衰减为有效迭代器的指针。作为指向 const char 的指针(迭代器),被取消引用的 const char 将被转换为 int 并添加为 vector 的元素。无论如何,该代码具有UB,因为 a b 没有引用有效范围,<无法从 a 访问code> b 。

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

这篇关于构建一个向量&lt; int&gt;。具有2个字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆