Hi!

I am looking for something to compact the clear and push_back in one line...

std::vector<int> v(3,100);

v.clear();
v.push_back(4);

I have thought that vector::swap may be usefull for this task but still figuring out how.

Any sugestion or idea?

Thank you in advance!

I am looking for something to compact the clear and push_back in one line...

Why?

Any sugestion or idea?

Nothing built into std::vector presently supports this. You'd have to add at least one line to get rid of one line, which nets you nothing.

>>I am looking for something to compact the clear and push_back in one line..

I don't see any point in doing this, but what about:

v.clear(); v.push_back(4);

or, if you really want it to be one expression:

std::vector<int>(1,4).swap(v);

or, if you really want it to be one expression:

std::vector<int>(1,4).swap(v);

I was looking for this,

Yes as you say it is probably not of much use, at least it is enough for consolidating some c++

Thank you!

You really haven't explained why you want to do that. Is it some sort of misguided attempt at condensation/optimization?

You do realize that this will probably create a larger executable because of the stuff that happens "under the hood" inside the class, don't you?

Edited 5 Years Ago by Fbody: n/a

v.assign( 1U, 4 ) ; // usually more efficient than create temporary vector and then swap
v = { 4 } ; // only in C++ 2011

Edited 5 Years Ago by vijayan121: n/a

You really haven't explained why you want to do that. Is it some sort of misguided attempt at condensation/optimization?

I just wanted to know how, though I realize it does not seem a good solution

You do realize that this will probably create a larger executable because of the stuff that happens "under the hood" inside the class, don't you?

I don't

Thank you vijayan121!

well for me these work

v.assign( 1U, 4 ) ;
std::vector<int>(1,4).swap(v);

Though it is true that the size of the executable is significantly bigger than using the clear&push_back solution, probably it will be faster too

This question has already been answered. Start a new discussion instead.