1

Vector function emplace() My emplace function does not work. Any help would be appreciated

vector <int> vec1; vector <int> vec2(4,0); vector <int>::iterator iter1; vector <int>::iterator iter2; srand(time(NULL)); for(i=0; i<5; i++){ n =rand()%10+1; vec1.push_back(n); } for(iter1=vec1.begin();iter1<vec1.end();iter1++){ for(iter2=vec2.begin();iter2<vec2.end();iter2++){ if(*iter1<=*iter2){ //vec2.emplace(iter1,*iter1); //print(); } } } 
1
  • It looks like your if condition won't enter unless the value in vector1 is 0. Even in that case, it's not really doing what you want. Are you sure the issue is with emplace and not with the if? Can you explain what you mean when you say that your "emplace function does not work"? As an aside, you might want to reconsider how to sort vector2, there are a number of better algorithms out there. en.wikipedia.org/wiki/… Commented Mar 2, 2016 at 5:02

2 Answers 2

2
for(iter2=vec2.begin();iter2<vec2.end();iter2++){ 

Because vec2 starts populated with four values of 0, you will never find an element where *iter1 <= *iter2 unless *iter1 == 0.

Instead of zero-initializing it to avoid allocations, you want to reserve space.

vec2.reserve(vec1.size()); 

and then instead of a for loop you can use std::lower_bound to find the insert location:

#include <iostream> #include <vector> #include <algorithm> void print_vec(const char* label, const std::vector<int>& vec) { std::cout << label << ": "; for (int v : vec) { std::cout << v << ", "; } std::cout << "\n"; } int main() { std::vector <int> vec1 { 4, 1, 2, 2, 5 }; std::vector <int> vec2; print_vec("v1", vec1); vec2.reserve(vec1.size()); for (int v : vec1) { auto it = std::lower_bound(vec2.begin(), vec2.end(), v); if (it == vec2.end() || *it != v) vec2.emplace(it, v); print_vec("v2", vec2); } print_vec("Fin", vec2); return 0; } 

Live demo: http://ideone.com/o5td9K

Sign up to request clarification or add additional context in comments.

Comments

0

What you are trying to do is like insertion sort. https://en.wikipedia.org/wiki/Insertion_sort has the pseudo-code. At each step you will check every element in vector 2 and place the new element where it belongs (while loop).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.