conditional push_back

G

gelbeiche

I have a std::list and I want extend the content of
the list (append a value) only if the value not
already exist.
E.g. I can write for a std::list<int> :

A)
if ( std::find(l.begin(),l.end(), 3) == l.end() )
l.insert(l.end(),3);

or

B)
if ( std::find(l.begin(),l.end(), 3) == l.end() )
l.push_back(3);

I have two questions:
1) Is there a better respectively shorter way to
express this ?
2) Which of both inserts (A or B) is the better one ?
 
S

Siemel Naran

I have a std::list and I want extend the content of
the list (append a value) only if the value not
already exist.
E.g. I can write for a std::list<int> :

A)
if ( std::find(l.begin(),l.end(), 3) == l.end() )
l.insert(l.end(),3);

or

B)
if ( std::find(l.begin(),l.end(), 3) == l.end() )
l.push_back(3);

I have two questions:
1) Is there a better respectively shorter way to
express this ?
2) Which of both inserts (A or B) is the better one ?

1) Would a std::set<int> be what you want?
2) They're probably the same.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,667
Latest member
DaniloB294

Latest Threads

Top