复制到矢量给出段错误
copy to vector giving segfault
我正在尝试将矢量数据从sample
复制到Y
,如下所示
std::map<std::string, std::vector<double > >sample;
std::map<std::string, std::vector<double > >::iterator it1=sample.begin(), end1=sample.end();
std::vector<double> Y;
并且我使用以下代码:
while (it1 != end1) {
std::copy(it1->second.begin(), it1->second.end(), std::ostream_iterator<double>(std::cout, " "));
++it1;
}
它可以正常打印输出,但是当我用下面的块替换上面的 std::copy 块时,我得到一个段错误。
while (it1 != end1) {
std::copy(it1->second.begin(), it1->second.end(), Y.end());
++it1;
}
我只想将它的内容1->秒复制到 Y。为什么它不起作用,我该如何解决?
显然,您希望将对象插入到向量中。但是,std::copy()
只是获取传递的迭代器并写入它们。begin()
和end()
迭代器获取的迭代器不执行任何插入。你想要使用的是这样的:
std::copy(it1->second.begin(), it1->second.end(), std::back_inserter(Y));
std::back_inserter()
函数模板是迭代器的工厂函数,使用push_back()
参数追加对象。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// your code goes here
vector<int> vec;
vector<int> test;
vec.push_back(1);
//test.push_back(0);
copy(vec.begin(),vec.begin()+1,test.begin());
cout << *(test.begin());
return 0;
}
输出:运行时错误时间:0 内存:3424 信号:11
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// your code goes here
vector<int> vec;
vector<int> test;
vec.push_back(1);
test.push_back(0);
copy(vec.begin(),vec.begin()+1,test.begin());
cout << *(test.begin());
return 0;
}
输出:*成功时间:0 内存:3428 信号:0*
1
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// your code goes here
vector<int> vec;
vector<int> test(5);
vec.push_back(1);
//test.push_back(0);
copy(vec.begin(),vec.begin()+1,test.begin());
cout << *(test.begin());
return 0;
}
成功时间:0 内存:3428 信号:0
1
所以原因是你没有启动向量,vector.begin() 指向某个受限制的地方!当您使用 back_inserter(vector) 时,它会返回一个back_insert_interator内部使用vector.push_back而不是*(顺从)操作。所以back_inserter有效!
相关文章:
- 为什么PyImport_ImportModule python 3.7.2 中出现段错误?
- 为什么在访问 vtkRenderWindow 的"交互器"变量时会发生段错误?
- 全局向量导致 C++ 程序结束时出现段错误
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 更改条件段错误
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 注册对对象工厂的调用会导致段错误
- pthread_create在构造函数段错误中
- Nanoflann发现邻居提出段错误
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 具有unique_ptr的 CRTP 会导致段错误
- 增强纤维work_stealing屏障会导致段错误
- 当我返回指向结构的指针向量时出现段错误
- C++为什么我的代码没有爆炸/段错误?
- Pthread段错误,使用指向main中变量的指针
- C++ 模板中的段错误
- 相当于Windows/MSVC上的段错误?
- 为什么我的 LLVM JIT 实现出现段错误?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?