0

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!

5
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by tikoti
0

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.

1

>>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);
0

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!

0

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 by Fbody: n/a

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

Edited by vijayan121: n/a

0

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

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.