gpt4 book ai didi

c++ - 空花括号 {} 作为范围的结尾

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:29:02 29 4
gpt4 key购买 nike

我在 XCode、Yosemite 上运行。

以下代码已编译但在运行时崩溃,为什么?

我故意在第二个 std::copy 中使用“{}”作为“范围结束”。

我试验这段代码是因为有一个工作示例使用“{}”作为“默认构造的流迭代器作为范围的末尾”。

那么,为什么那个(见第二个代码)一个工作正常而这个(第一个代码)一个失败了?

#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
using namespace std;

int main()
{
vector<int> coll1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// copy the elements of coll1 into coll2 by appending them
vector<int> coll2;
copy (coll1.cbegin(), coll1.cend(), // source
back_inserter(coll2)); // destination

vector<int> coll3;
copy (coll1.begin(), {},
back_inserter(coll3));

}

以下代码来自 The C++ Standard Library 第二版。

带有“//end of source”的行可以是“istream_iterator()”或简单的“{}”

两者都有效,因为:引自书中

“请注意,自 C++11 起,您可以传递空花括号而不是默认构造的流迭代器作为范围的结尾。这是有效的,因为定义源范围结尾的参数类型是从定义源范围开始的前一个参数推导出来的。”

/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <iterator>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
using namespace std;

int main()
{
vector<string> coll;

// read all words from the standard input
// - source: all strings until end-of-file (or error)
// - destination: coll (inserting)
copy (istream_iterator<string>(cin), // start of source
{}, // end of source
back_inserter(coll)); // destination

// sort elements
sort (coll.begin(), coll.end());

// print all elements without duplicates
// - source: coll
// - destination: standard output (with newline between elements)
unique_copy (coll.cbegin(), coll.cend(), // source
ostream_iterator<string>(cout,"\n")); // destination
}

最佳答案

第一个失败是因为您的迭代器类型不是 stream_iterator

对于 stream_iterator 情况,默认构造函数具有特殊含义 - EOF。表示容器末尾的迭代器不是默认构造的。 (在实践中,对于简单的容器,迭代器可以只是指针)。

除流迭代器之外的默认构造迭代器通常没有多大意义,并且在这种情况下不具有您想要的语义。

(除了流迭代器之外,来自 boost 的其他一些迭代器确实遵循与流迭代器相同的模式)。

关于c++ - 空花括号 {} 作为范围的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30124122/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com