Reputation: 2035
I am getting the run time error in following code. Please let me know can i copy vector elements in set?
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main()
{
vector<int> v;
set<int> kk;
set<int>::iterator itr;
for (int i = 0; i < 6; i++)
{
v.push_back(i * 2);
}
copy(v.begin(), v.end(), inserter(kk, itr));
}
Upvotes: 21
Views: 29172
Reputation: 141810
You are not initialising itr
:
set<int>::iterator itr = kk.begin();
Or remove itr
entirely:
copy(v.begin(), v.end(), inserter(kk, kk.begin()));
In this instance, you could simply initialise kk
thus (but if you want to add to kk
follow the line above):
set<int> kk(v.begin(), v.end());
Upvotes: 32
Reputation: 61519
If the goal is to create a set from the vector elements (rather than update an already existing set that might have some elements in it), then do that, by using the constructor:
set<int> s(v.begin(), v.end());
Upvotes: 17
Reputation: 264411
Try:
copy(v.begin(), v.end(),inserter(kk, kk.end() ));
// ^^^^^^^^ You need a real iterator.
Upvotes: 2
Reputation: 1614
You need to initialize the iterator.
set<int>::iterator itr = kk.end();
Upvotes: 2