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?
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.
#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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With