开发者

finding the common elements of vectors which are inside another map

dear all, i have a map, defined as map<int, vector<int> > my_map. So, for example it looks like as follows,

my_map=
0 1 2 6 5 4
1 0 2 3 4 5
2 0 1 4
3 1
4 1 2 0 7 5 6
5 1 0 6 4
6 0 5 4
7 4

vector<int> element_common(map<int, vector<int> > &my_map, int s1, int s2){
     vector<int> common2;
     vector<int> first_vector=my_map[s1];     
     vector<int>::iterator snd_vector_begin= my_map[s2].begin();
     vector<int>::iterator snd_vector_end= my_map[s2].end();          
     for (vector<int>::iterator any=first_vector.begin();
                            any!=first_vector.end();
                            any++){            
         // check if any is in other_list
         vector<int>::iterator any_in_snd_vector_iterator= find (snd_vector_begin,snd_vector_end, *any);            
         if(any_in_snd_vector_iterator==snd_vector_end){
            common2.push_back(*any); 
            }
         }
     return common2开发者_如何学编程;

i wrote a function above function to get common elements from the vector parts which are relevant to 2 given keys. when keys are equal to s1 and s2, i.e. s1=1 and s2=4. then my function should give me 0,2,5. but i got 3,4. please help me to rectify my function.


If you can guarantee your vectors are sorted then you can improve your performance substantially from O(mn) to O(m + n):

std::vector<int> common;
std::set_intersection(vec1.begin(), vec1.end(),
                      vec2.begin(), vec2.end(),
                      std::back_inserter(common));


You got the test exactly backwards:

if(any_in_2nd_vector_iterator==2nd_vector_end){

is true when the element ISN'T FOUND in the second vector. Try !=.

Then, you can avoid needless copying of vectors by using a reference:

const vector<int>& first_vector=my_map[s1];

and if your vectors get much larger, it may be faster to do a hash lookup (or pre-sorted merge if the vectors are always kept sorted) instead of a call to find which has to check every element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜