初始化向量< string>双花括号 [英] Initializing vector<string> with double curly braces
问题描述
在下面的示例中,有人可以解释用双花括号和单花括号初始化之间的行为差异吗?
Can someone explain the difference in behavior between initializing with double and single curly braces in the example below?
代码#1:
vector<string> v = {"a", "b"};
string c(v[0] + v[1]);
cout << "c = " << c;
cout << "c.c_str() = " << c.c_str();
输出#1:
c = ab
c.c_str() = ab
代码#2:
vector<string> v = {{"a", "b"}};
string c(v[0] + v[1]);
cout << "c = " << c;
cout << "c.c_str() = " << c.c_str();
输出2:
c = a\acke�Z\
c.c_str() = a
推荐答案
隐式转换中心。就是这样。
Implicit conversion central. That's what's going on.
-
vector< string> v = { a, b};
通过提供带有两个元素的初始化列表来初始化向量。从字符串文字中初始化两个std :: string
s,然后将其复制到向量中。
vector<string> v = {"a", "b"};
You initialize the vector by providing an initializer list with two elements. The twostd::string
s are initialized from the string literals, and then copied into the vector.
vector< string> v = {{ a, b}};
通过为初始化器提供 one 元素来初始化向量。单个 std :: string
是从具有两个元素的初始化程序初始化的。访问向量的第二个元素具有不确定的行为。
vector<string> v = {{"a", "b"}};
You initialize the vector by providing an initializer with one element. And that single std::string
is initialized from an initializer that has two elements. Accessing the second element of the vector has undefined behavior.
现在,这是有趣的部分。甚至在您访问 v [1]
之前,您的第二个代码段都具有未定义的行为。重载解析(构造单个 std :: string
)选择一个构造函数。最好的可行方法是:
Now, here's the fun part. Your second snippet has undefined behavior even before you access v[1]
. Overload resolution (to construct the single std::string
) picks a constructor. The best viable one, is this:
template< class InputIt >
basic_string( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
将 InputIt
推导出为 char const [2]
(和功能参数调整,将其更改为 char const *
)。既然这些并不是真正的迭代器,那么一切都将变得一团糟。
With InputIt
being deduced as char const [2]
(and function parameter adjustment, turning it to char const*
). Since those aren't really iterators, all hell breaks loose.
这篇关于初始化向量< string>双花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!