Finding common assetes in vector lists

Find all the COMMON assets between two levels.

The passed in asset lists may contain duplicate values, but the result must contain NO duplicates.

You can assume two assets are equivalent if and only if they are located at the same memory address.

Implement the FindCommonAssets function as optimally as possible, given levels with thousands of assets and (potentially) many duplicate entries.

The result should contain a single unique reference to every asset that is contained in BOTH level lists.


I really need help with the robustness of this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Vector with common assets inside
std::vector<Asset*> commonAssets;
	
bool duplicate = false;

// Checking each element in level 1 against the elements in level 2
for(Asset l1 : LevelOneAssets){
	for(Asset l2 : LevelTwoAssets){
	        // if elements address are equal, check if common assets already has that element inside
	        if(*l1 == *l2){
	        // check through all common assets against the new common element to see if any duplicates
	                for(Asset dup : commonAssets){
			if(*l1 == *dup){
				duplicate = true;	
			}
		}
		if(duplicate == false){
		        commonAssets.push_back(l1);				
		}
		duplicate = false;
	}
}
	}
	outUniqueCommonAssets = commonAssets;
> two assets are equivalent if and only if they are located at the same memory address.
if(*l1 == *l2)
¿are you comparing memory address?

l1 is an `Asset', ¿what does the * operator do to it?
... but then you do commonAssets.push_back(l1); where `commonAssets' stores pointers...

¿does your code even compile?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <vector>
#include <set>
#include <iterator>
#include <algorithm>

template< typename T >
std::vector<T> common_elements( const std::set<T>& a, const std::set<T>& b )
{
    std::vector<T> common ;

    // http://en.cppreference.com/w/cpp/algorithm/set_intersection
    // http://en.cppreference.com/w/cpp/iterator/back_inserter
    std::set_intersection( std::begin(a), std::end(a), std::begin(b), std::end(b),
                           std::back_inserter(common) ) ;

    return common ;
}

struct Asset { /* ... */ } ;

std::vector<Asset*> FindCommonAssets( const std::vector<Asset*>& first,
                                      const std::vector<Asset*>& second )
{
    return common_elements( std::set<Asset*>{ std::begin(first), std::end(first) },
                            std::set<Asset*>{ std::begin(second), std::end(second) } ) ;
}

http://coliru.stacked-crooked.com/a/055c8438082967ef
http://rextester.com/DPX87488
Topic archived. No new replies allowed.