更新时间:2023-11-12 17:00:58
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*
.