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]

# 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 >
