问题描述
我在一个项目中遇到了一段C ++代码,该代码用两个输入初始化一个向量.
其中一个输入是一个现有数组,另一个是相同的数组加上数组长度.
我在另一个站点上找到了类似的代码段:
//创建一个字符串对象数组std :: string arr [] = {第一",秒",第三",第四"};//用字符串数组初始化向量std :: vector< std :: string>vecOfStr(arr,arr + sizeof(arr)/sizeof(std :: string));for(std :: string str:vecOfStr)std :: cout<<str<<std :: endl;
有人可以解释 arr + sizeof(arr)/sizeof(std :: string)
是什么吗?
引用此代码的网站说,这是所使用的相应构造函数:
vector(首先输入InputIterator,最后输入InputIterator,const allocator_type& alloc = allocator_type());
arr
本身的类型为 std :: string [4]
.传递给函数时,它已衰减指向第一个元素的指针.在表达式 arr + sizeof(arr)/sizeof(std :: string)
中, arr
的首次出现再次被衰减.第二个不是.因此, sizeof(arr)/sizeof(std :: string)
的计算结果为 4
,这是数组范围.然后,整个表达式 arr + sizeof(arr)/sizeof(std :: string)
会得出指向 arr
中最后一个元素之后位置的指针.这通常称为场外迭代器.这有效地调用了构造函数 vector(首先是InputIterator,最后是InputIterator,...)
,其中 InputIterator
用 std :: string *
实例化./p>
I came across a piece of C++ code in one of my projects that initializes a vector with two inputs.
One of the inputs is an existing array, and the other is the same array plus the array length.
I found a similar piece of code on another site:
// Create an array of string objects
std::string arr[] = {"first", "sec", "third", "fourth"};
// Initialize vector with a string array
std::vector<std::string> vecOfStr(arr, arr + sizeof(arr)/sizeof(std::string));
for(std::string str : vecOfStr)
std::cout << str << std::endl;
Can someone explain what arr + sizeof(arr)/sizeof(std::string)
is?
The website that this code was referenced in said that this was the corresponding constructor used:
vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());
arr
itself is of type std::string[4]
. When passed to a function, it is decayed to pointer to the first element. In the expression arr + sizeof(arr)/sizeof(std::string)
, the first occurrence of arr
is again decayed. The second is not. sizeof(arr)/sizeof(std::string)
therefore evaluates to 4
which is the array extent. The whole expression arr + sizeof(arr)/sizeof(std::string)
then evaluates to a pointer to the position past the final element in arr
. This is usually called the off-the-end iterator. This effectively invokes the constructor vector(InputIterator first, InputIterator last, ...)
where InputIterator
is instantiated with std::string*
.
这篇关于具有两个输入参数的std :: vector构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!