我正在运行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));
}
以下代码来自《C++标准库第二版》。
带有“// 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
}