Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy to vector giving segfault

Tags:

c++

I am trying to copy the vector data from sample to Y as below

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; 

and am using the following code:

 while (it1 != end1) {
  std::copy(it1->second.begin(), it1->second.end(), std::ostream_iterator<double>(std::cout, " "));
++it1;
}

It prints the output ok, however when I replace the above std::copy block with the below, I get a segfault.

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

I just want to copy the contents of it1->second to Y. Why is it not working and how do I fix it?

like image 915
user1155299 Avatar asked Dec 01 '22 22:12

user1155299


2 Answers

Obviously, you want to insert objects into your vector. However, std::copy() merely takes the iterators passed and writes to them. The iterators obtained by the begin() and end() iterators don't do any insertion. What you want to use is something like this:

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

The std::back_inserter() function template is a factory function for an iterator using push_back() on its argument to append objects.

like image 119
Dietmar Kühl Avatar answered Dec 17 '22 13:12

Dietmar Kühl


#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;
}

output: Runtime error time: 0 memory: 3424 signal: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;
}

output: *Success time: 0 memory: 3428 signal: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;
}

Success time: 0 memory: 3428 signal:0

1

SO the reason is that you didn't initilize the vector,the vector.begin() point to somewhere restricted! when you use a back_inserter(vector) it return a back_insert_interator that internally use a vector.push_back rather than a *(deference) operation. So back_inserter works!

like image 31
Jack Chin Avatar answered Dec 17 '22 15:12

Jack Chin