Lists

If i have 5 STL lists with, lets say, 10 different numbers that are unique to each list, is there a way where, in STL perhaps, I can just sift out all the numbers that are common to all 5 lists?
Regards
John
[225 byte] By [Vaderman] at [2007-11-18 21:42:12]
# 1 Re: Lists
It is not clear what you need.
Do you want to delete the common numbers, do you want a single container (as a result) that contains no common?

Regards,
Guy
Guysl at 2007-11-9 0:34:26 >
# 2 Re: Lists
the other way round! :)
Vaderman at 2007-11-9 0:35:26 >
# 3 Re: Lists
The other way around means you need only the common numbers?
if so, you can sort the lists using list's member function 'sort()'
and then use the algorithm std::set_intersection.
Guysl at 2007-11-9 0:36:22 >
# 4 Re: Lists
...Or as an alternative you can use std::set as the following
(the 'getCommon' function):

#include<iostream>
#include<list>
#include<vector>
#include<iterator>
#include<set>

typedef std::vector<std::list<int> > vecLists;
typedef std::list<int>::iterator listIter;
typedef std::list<int>::const_iterator constListIter;
typedef std::set<int> setInt;
//==============================================
void print(const vecLists& lists)
{
for(int i=0; i<lists.size(); ++i)
{
copy(lists[i].begin(), lists[i].end(), std::ostream_iterator<int>(std::cout, " "));
std::cout<<std::endl;
}
}
//==============================================
void getCommon(const vecLists& lists, setInt& result)
{
setInt Set;

//insert all lists values into std::set. The 'rejected' values are 'common'
for(int i=0; i<lists.size(); ++i)
for(constListIter Iter = lists[i].begin(); Iter!=lists[i].end(); ++Iter)
if(!Set.insert(*Iter).second) //set.insert fails when a value already exists
result.insert(*Iter); //... so that value is a 'common' value
}
//==============================================
int main()
{
vecLists lists;

//initiate lists with random values
for(int i=0;i<5;i++)
{
lists.push_back(std::list<int>(10));
for(listIter Iter = lists[i].begin(); Iter!=lists[i].end(); ++Iter)
*Iter = rand()%20;
}

std::cout << "Original values are:" << std::endl;
print(lists);

//find common values
setInt result;
getCommon(lists,result);

//print common values
std::cout << "Common values are:" << std::endl;
copy(result.begin(), result.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
system("pause");
}
Guysl at 2007-11-9 0:37:27 >
# 5 Re: Lists
Originally posted by Guysl
...Or as an alternative you can use std::set as the following


Good idea.
SkyMountain at 2007-11-9 0:38:21 >
# 6 Re: Lists
thanx guys.
Vaderman at 2007-11-9 0:39:29 >