Cro*_*dee 130 c++ copy stdvector stdset
我需要复制std::set到std::vector:
std::set <double> input;
input.insert(5);
input.insert(6);
std::vector <double> output;
std::copy(input.begin(), input.end(), output.begin()); //Error: Vector iterator not dereferencable
Run Code Online (Sandbox Code Playgroud)
问题出在哪儿?
Jam*_*lis 203
你需要使用back_inserter:
std::copy(input.begin(), input.end(), std::back_inserter(output));
Run Code Online (Sandbox Code Playgroud)
std::copy不会向要插入的容器添加元素:它不能; 它只有一个迭代器进入容器.因此,如果直接将输出迭代器传递给std::copy,则必须确保它指向一个至少足以容纳输入范围的范围.
std::back_inserter创建一个输出迭代器,push_back为每个元素调用一个容器,因此每个元素都插入到容器中.或者,您可以创建足够数量的元素std::vector来保存要复制的范围:
std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用std::vector范围构造函数:
std::vector<double> output(input.begin(), input.end());
Run Code Online (Sandbox Code Playgroud)
Jac*_*cob 114
只需使用构造函数来获取迭代器的向量:
std::set<T> s;
//...
std::vector v( s.begin(), s.end() );
Run Code Online (Sandbox Code Playgroud)
假设您只想要v中的s内容,并且在将数据复制到v之前没有任何内容.
Ted*_*dyC 36
这是另一种替代方案vector::assign:
theVector.assign(theSet.begin(), theSet.end());
Run Code Online (Sandbox Code Playgroud)
Mar*_*lon 23
您没有在矢量对象中保留足够的空间来保存集合的内容.
std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
Run Code Online (Sandbox Code Playgroud)