复制到矢量给segfault

时间:2012-04-30 02:40:05

标签: c++

我正在尝试将矢量数据从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;
}

它打印输出ok,但是当我用下面的代替上面的std :: copy块时,我得到一个段错误。

 while (it1 != end1) {
std::copy(it1->second.begin(), it1->second.end(), Y.end());
++it1;
}

我只想将it1-&gt;秒的内容复制到Y.为什么它不起作用,我该如何解决?

2 个答案:

答案 0 :(得分:12)

显然,您希望将对象插入到矢量中。但是,std::copy()只是传递迭代器并写入它们。 begin()end()迭代器获得的迭代器不会进行任何插入。你想要使用的是这样的:

std::copy(it1->second.begin(), it1->second.end(), std::back_inserter(Y));

std::back_inserter()函数模板是迭代器的工厂函数,在其参数上使用push_back()来追加对象。

答案 1 :(得分:0)

#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)时,它会返回一个内部使用a的back_insert_interator vector.push_back而不是*(deference)操作。所以back_inserter有效!

相关问题