473,811 Members | 2,963 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A function for a generic STL container

Hi I want to write a function which erases al the repeated elements in a
range. How should be the prototype?

template <class Iterator>
void eraseRepeated(I terator begin, Iterator end);

doesn't work because I need the container to write: container.erase (p),
where p is an iterator.
Jul 23 '05
19 2258
Kristo wrote:
Nafai wrote:
Kristo escribió:
> Nafai wrote:
>>
>>Let's see. It's quite simple. I have a collection C (ie. list or
>>vector):
>>C=(1 4 4 2 1 1 4) and I get: C'=(1 4 2)
>>
>>The algorithm is just this:
>>
>>insert all elements of C into a set.
>>
>>iterate through C and check if each element is in the set.
>>If it is, erase it from the set.
>>If it isn't erase it from C.
>>
>>Or even more simpler (and suitable for any collection):
>>
>>...
>>If it is, erase it from the set and insert it into C'.
>>If it isn't do nothing.
>>
>>
>>I just need to know how to declare the prototype!! ("template". ..)
>
>
> Does this suit you?
>
> template <class T>
> void eraseRepeated(T &container);
>
> Kristo
>


No, it doesn't. This doesn't work:

template <class T>
void f(T& Container)
{
T::iterator it; // <- parse error before token ';'
it = Container.begin ();
...
}


That's because you forgot the typename keyword. The compiler has no
other way of knowing that T::iterator is a type.

typename T::iterator it;

Kristo


But I also have to know the type of elements that contains "Container" .

For example, if T=list<T2>, I need to declare a std::set<T2> as a local
variable:

template <class T>
void f(T& Container)
{
std::set<????> s;
typename T::iterator it;
...
}
Jul 23 '05 #11
Nafai wrote:
Kristo wrote:
Nafai wrote:
Kristo escribió:
> Nafai wrote:
>>
>>Let's see. It's quite simple. I have a collection C (ie. list or
>>vector):
>>C=(1 4 4 2 1 1 4) and I get: C'=(1 4 2)
>>
>>The algorithm is just this:
>>
>>insert all elements of C into a set.
>>
>>iterate through C and check if each element is in the set.
>>If it is, erase it from the set.
>>If it isn't erase it from C.
>>
>>Or even more simpler (and suitable for any collection):
>>
>>...
>>If it is, erase it from the set and insert it into C'.
>>If it isn't do nothing.
>>
>>
>>I just need to know how to declare the prototype!! ("template". ..)
>
>
> Does this suit you?
>
> template <class T>
> void eraseRepeated(T &container);
>
> Kristo
>

No, it doesn't. This doesn't work:

template <class T>
void f(T& Container)
{
T::iterator it; // <- parse error before token ';'
it = Container.begin ();
...
}


That's because you forgot the typename keyword. The compiler has no
other way of knowing that T::iterator is a type.

typename T::iterator it;

Kristo


But I also have to know the type of elements that contains "Container" .

For example, if T=list<T2>, I need to declare a std::set<T2> as a local
variable:

template <class T>
void f(T& Container)
{
std::set<????> s;
typename T::iterator it;
...
}


Here is my final solution. Any suggestion to improve it?

template <class T, class Container>
void eraseRepeated(C ontainer& c)
{
std::set<T> s;
typename Container::iter ator itc;
for(itc=c.begin ();itc!=c.end() ;++itc)
{
s.insert(*itc);
}

typename std::set<T>::it erator its;

itc=c.begin();
while(itc!=c.en d())
{
its=s.find(*itc );
if(its!=s.end() )
{
s.erase(its);
itc++;
}
else
{
itc=c.erase(itc );
}
}
}
Example of use:

int main()
{
std::list<int> l(3,3);
l.push_back(5); l.push_back(3); l.push_back(2); l.push_back(5);

std::vector<cha r> v;
v.push_back('a' );v.push_back(' b');
v.push_back('a' );v.push_back(' a');
v.push_back('c' );v.push_back(' b');

copy(l.begin(), l.end(),ostream _iterator<int>( cout, " "));
cout << endl;

eraseRepeated< int, list<int> >(l); // ANY WAY TO MAKE IT SIMPLER?:
// eraseRepeated< list<int> >(l); for example.

copy(l.begin(), l.end(),ostream _iterator<int>( cout, " "));
cout << endl;

copy(v.begin(), v.end(),ostream _iterator<char> (cout, " "));
cout << endl;
eraseRepeated< char, vector<char> >(v);
copy(v.begin(), v.end(),ostream _iterator<char> (cout, " "));
cout << endl;
}

Output:

3 3 3 5 3 2 5
3 5 2
a b a a c b
a b c

Jul 23 '05 #12

Nafai wrote:
Here is my final solution. Any suggestion to improve it?

template <class T, class Container>
void eraseRepeated(C ontainer& c)
{
std::set<T> s;
typename Container::iter ator itc;
for(itc=c.begin ();itc!=c.end() ;++itc)
{
s.insert(*itc);
}

typename std::set<T>::it erator its;

itc=c.begin();
while(itc!=c.en d())
{
its=s.find(*itc );
if(its!=s.end() )
{
s.erase(its);
itc++;
}
else
{
itc=c.erase(itc );
}
}
}


You cannot call 'c.erase' while looping over 'c' with
'Container::ite rator's as this invalidates 'itc' in some cases causing
'itc++' to produce undefined behavior. Furthermore, not all containers
(e.g., Associative Containers) return a valid iterator from 'erase'.

It seems like you want to sort 'c', copy unique elements to a temporary
'Container' object, 'c2', and then 'swap' between 'c' and 'c2'.

You can even better performance if you tmplatize on container type
*and* element type. Then you can specialize for sorted containers by
simply copying repeated elements into a second container of the same
type and finally calling 'swap' to get the result back into the
original container.

In any case, except where radix-sort is appropriate (again, a
specialization) , any solution is going to be O(n log n).

/david

Jul 23 '05 #13
You should very carefully consider whether or not you really don't want
to use std::unique(). Here are the unsorted_unique () and related
algorithms from my STL Extensions library, and it does what I believe
you want done. But it is extremely expensive. Choose your tools
wisely.

/* ---

25.2.8
template< class ForwardIterator , class OutputIterator, class
BinaryPredicate >
OutputIterator unsorted_unique _copy(ForwardIt erator first,
InputIterator last, OutputIterator result, BinaryPredicate pred)

template< class ForwardIterator , class OutputIterator>
OutputIterator unsorted_unique _copy(ForwardIt erator first,
InputIterator last, OutputIterator result)

template< class ForwardIterator , class OutputIterator, class
BinaryPredicate >
ForwardIterator unsorted_unique (ForwardIterato r first,
ForwardIterator last, OutputIterator result, BinaryPredicate pred)

template< class ForwardIterator , class OutputIterator>
ForwardIterator unsorted_unique (ForwardIterato r first,
ForwardIterator last, OutputIterator result)

Requires :

The ranges [first, last) and [result, result+last-first) shall not
overlap

Effects :

Eliminates all but the first occurance of any element referred to by
the iterator i in the range [first, last).
The range [first, last) does not need to be sorted before executing
unsorted_unique _copy.

Complexity :

If the range [first, last) is not empty, (n^2 + n) / 2 applications
of the comparison predicate or operator.
Otherwise, no applications of the predicate.

Returns :

The end of the resulting range.

--- */

template< class ForwardIterator , class OutputIterator, class
BinaryPredicate >
OutputIterator unsorted_unique _copy(ForwardIt erator first,
ForwardIterator last, OutputIterator result, BinaryPredicate pred)
{
for( ForwardIterator current = first; current != last; ++current )
{
// make sure this item isnt repeated previously in the source range
if( current == find_if(first, current, bind1st(pred,*c urrent)) )
// wasn't found, add to destination range
*result++ = *current;
}
return result;
}

template< class ForwardIterator , class OutputIterator>
OutputIterator unsorted_unique _copy(ForwardIt erator first,
ForwardIterator last, OutputIterator result)
{
for( ForwardIterator current = first; current != last; ++current )
{
// make sure this item isnt repeated previously in the source range
if( current == find(first, current, *current) )
// wasn't found, add to destination range
*result++ = *current;
}
return result;
}

template< class BidirectionalIt erator> inline
BidirectionalIt erator unsorted_unique (BidirectionalI terator first,
BidirectionalIt erator last)
{
for( ; first != last; ++first )
{
BidirectionalIt erator current = first;
for( ++current; current != last; )
{
if( *first == *current )
{
BidirectionalIt erator rotend(current) ;
++rotend;
rotate(current, rotend,last--);
}
else
++current;
}
}
return last;
}

template< class BidirectionalIt erator, class BinaryPredicate >
BidirectionalIt erator unsorted_unique (BidirectionalI terator first,
BidirectionalIt erator last, BinaryPredicate pred)
{
for( ; first != last; ++first )
{
BidirectionalIt erator current(first);
for( current++; current != last; )
{
if( pred(*first, *current) )
{
BidirectionalIt erator rotend(current) ;
rotend++;
rotate(current, rotend,last--);
}
else
++current;
}
}
return last;
}

</dib>

Jul 23 '05 #14
Nafai wrote:

But I also have to know the type of elements that contains "Container" .

For example, if T=list<T2>, I need to declare a std::set<T2> as a local
variable:

template <class T>
void f(T& Container)
{
std::set<????> s;
typename T::iterator it;
...
}


How about this:

template <typename Container>
void eraseRepeated(C ontainer& c)
{
typedef typename Container::valu e_type T;

std::set<T> s;
typename Container::iter ator iter;

// ...
}
Jul 23 '05 #15
Nafai wrote:
Let's see. It's quite simple. I have a collection C (ie. list or
vector):
C=(1 4 4 2 1 1 4) and I get: C'=(1 4 2)

The algorithm is just this:

insert all elements of C into a set.


One thing I forgot to mention: this step is O(n log n), so you're not
gaining anything over sorting and then calling std::unique.

[snip the rest of the algorithm]

Kristo

Jul 23 '05 #16
da********@warp mail.net escribió:
Nafai wrote:

Here is my final solution. Any suggestion to improve it?

template <class T, class Container>
void eraseRepeated(C ontainer& c)
{
std::set<T> s;
typename Container::iter ator itc;
for(itc=c.begin ();itc!=c.end() ;++itc)
{
s.insert(*itc);
}

typename std::set<T>::it erator its;

itc=c.begin();
while(itc!=c.en d())
{
its=s.find(*itc );
if(its!=s.end() )
{
s.erase(its);
itc++;
}
else
{
itc=c.erase(itc );
}
}
}

You cannot call 'c.erase' while looping over 'c' with
'Container::ite rator's as this invalidates 'itc' in some cases causing
'itc++' to produce undefined behavior. Furthermore, not all containers
(e.g., Associative Containers) return a valid iterator from 'erase'.


For lists and vectors it works. And after calling c.erase(itc) I dont
write itc++, I do that after s.erase(its).
It seems like you want to sort 'c', copy unique elements to a temporary
'Container' object, 'c2', and then 'swap' between 'c' and 'c2'.
I don't want to sort c. That's because I don't sort and use unique.

For example:
I want: 3 1 3 2 3 2 --> 3 1 2
but not: 3 3 2 3 2 --> 1 2 2 3 3 3 --> 1 2 3
You can even better performance if you tmplatize on container type
*and* element type.
How do I do that?:

template < class T, class Container<T> >
void f(Container<T>& c);
....
f<int>(L);

or...

template < class T, class Container >
void f(Container& c);
....
f< int, list<int> >(L);

?
In any case, except where radix-sort is appropriate (again, a
specialization) , any solution is going to be O(n log n).

/david

Jul 23 '05 #17
Kristo escribió:
Nafai wrote:
Let's see. It's quite simple. I have a collection C (ie. list or
vector):
C=(1 4 4 2 1 1 4) and I get: C'=(1 4 2)

The algorithm is just this:

insert all elements of C into a set.

One thing I forgot to mention: this step is O(n log n), so you're not
gaining anything over sorting and then calling std::unique.

[snip the rest of the algorithm]

Kristo


But I don't want the elements to get sorted!

For example:
I want: 3 1 3 2 3 2 --> 3 1 2
but not: 3 3 2 3 2 --> 1 2 2 3 3 3 --> 1 2 3
Jul 23 '05 #18

Nafai wrote:
da********@warp mail.net escribió:
Nafai wrote:

Here is my final solution. Any suggestion to improve it?

[snip] You cannot call 'c.erase' while looping over 'c' with
'Container::ite rator's as this invalidates 'itc' in some cases causing 'itc++' to produce undefined behavior. Furthermore, not all containers (e.g., Associative Containers) return a valid iterator from 'erase'.

For lists and vectors it works. And after calling c.erase(itc) I dont write itc++, I do that after s.erase(its).
This is not useful to OP who asked about a solution given a generic
container.

The point about iterators and erase is that you can't always execute
'itc++' after executing 'c.erase(itc)', notwithstanding the fact that
not all container types return an iterator from 'erase'.
It seems like you want to sort 'c', copy unique elements to a temporary 'Container' object, 'c2', and then 'swap' between 'c' and 'c2'.


I don't want to sort c. That's because I don't sort and use unique.


Your example does not use 'unique'...
For example:
I want: 3 1 3 2 3 2 --> 3 1 2
but not: 3 3 2 3 2 --> 1 2 2 3 3 3 --> 1 2 3


....and 'unique' does not work this way. It requires an ordered
collection to be effective for the pupose stated by OP.
You can even better performance if you tmplatize on container type
*and* element type.


How do I do that?:


With either two template parameters or a template-template parameter.

/david

Jul 23 '05 #19
Nafai wrote:
Kristo escribió:
Nafai wrote:
Let's see. It's quite simple. I have a collection C (ie. list or
vector):
C=(1 4 4 2 1 1 4) and I get: C'=(1 4 2)

The algorithm is just this:

insert all elements of C into a set.

One thing I forgot to mention: this step is O(n log n), so you're not gaining anything over sorting and then calling std::unique.

[snip the rest of the algorithm]

Kristo


But I don't want the elements to get sorted!

For example:
I want: 3 1 3 2 3 2 --> 3 1 2
but not: 3 3 2 3 2 --> 1 2 2 3 3 3 --> 1 2 3


Whoops, that's right, you said that. I came up with an O(n^2)
algorithm that might work for you. It uses the prototype you initially
rejected. I'm sure you could modify it to suit your needs.

/* begin foo.cpp */
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <vector>

template <class Iterator>
Iterator eraseRepeated(I terator begin, Iterator end)
{
for (Iterator i = begin; i != end;)
{
Iterator prev = i++;
end = std::remove(i, end, *prev);
}

return end;
}

int main()
{
int a[] = {3, 1, 3, 2, 3, 2};

int *e = eraseRepeated(a , a+5);
std::copy(a, e, std::ostream_it erator<int>(std ::cout, " "));
std::cout << std::endl;

return 0;
}
/* end foo.cpp */

The output from this program is:
3 1 2

Hope this helps.

Kristo

Jul 23 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1612
by: Stewart Rogers | last post by:
Hi all, I have been working on an ASP.NET application that is a kind of wizard ( a list of sequential pages ). We built that application for the CLIENT-A and it worked fine. After six months CLIENT-B came along and and requested the same application but with little bit different requirements (both in terms of the front-end and back-end processing), so we had to create a new application for that client. Now came CLIENT-C !!!!!! I am...
2
1896
by: Luc Claustres | last post by:
I have a generic container such as: template<class T> class Container { // some data structure that store elements of type T } I use this container in a hierarchical manner, that is elements can be themselves containers:
1
2506
by: Anton Pervukhin | last post by:
Hi everybody! While trying to implement a generic sorting function which takes a member function(on which base the actual sort happens) as a parameter, I have met the problem that I need to use the result type of the member function and as I have understood there is no way in standart stl to extract it. While searching through this groop and in general, I could found some references to the problem in the following topic : ...
7
1155
by: Alfonso Morra | last post by:
I have written a class, and several of it's methods are function templates. When I compiled the code, I realized that I had made some typos in the code - but the compiler seemed to skip right over these obvious errors. I gre suspicious and enterred XXX in one of the function templates - and the compiler succesfully compile the code (obviously completely skipped my templated functions). I am using VC 7.1 Is this a "bug", (highly unlikely,...
4
1823
by: Anders | last post by:
Hi, I was wondering what is most efficient of the two. Is it more efficient to add server controls within the Itemtemplate and use OnItemDataBound to manipulate and databind the servercontrols. Or is better to send the DataItems via. a method/function from within the Itemtemplate (<%# call function %>) Id love to hear your thoughts. Anders
4
4937
by: Mitchel Haas | last post by:
Hello, Feeling a need for a generic tree container to supplement the available containers in the STL, I've created a generic tree container library (TCL). The library usage is very much like the containers in the STL, including iterator usage. Info on the library can be found here.. http://www.visuallandlord.com/developers_corner/open_source/tree_container_library/overview.php The library and sample code can be downloaded from this...
18
3498
by: Robbie Hatley | last post by:
A couple of days ago I dedecided to force myself to really learn exactly what "strtok" does, and how to use it. I figured I'd just look it up in some book and that would be that. I figured wrong! Firstly, Bjarne Stroustrup's "The C++ Programming Language" said: (nothing)
4
1731
by: Terence Wilson | last post by:
I'm having trouble designing a container for all the basic types(char, int, float, double). The container should be able to hold contiguous arrays of type T. I would like some kind of generic iterator for accessing the data that is type independent in order that I could write generic algorithms. Basically I need something like std::vector that does not require a compile type. I could use some kind of Variant for each element, but the...
6
5933
by: RandomElle | last post by:
Hi there I'm hoping someone can help me out with the use of the Eval function. I am using Access2003 under WinXP Pro. I can successfully use the Eval function and get it to call any function with or without parms. I know that any function that is passed to Eval() must be declared Public. It can be a Sub or Function, as long as it's Public. I even have it where the "function" evaluated by Eval can be in a form (class) module or in a standard...
0
9722
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10644
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.