复制到矢量给出段错误

copy to vector giving segfault

本文关键字:错误 段错误 复制      更新时间:2023-10-16

我正在尝试将矢量数据从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有效!