Puniith
Puniith

Reputation: 3

C++ Vector Operations

Is there any alternative for this? Performing a vector operation in multiples on certain condition?

i want to perform erase vector operation (n-1) times, just deleting only first element in a particular vector on a given if condition.

is it possible to do like this

if ( ret.size() == n ){
        (n-1)*order.erase(order.begin());
        (n-1)*quantity.erase(quantity.begin());
        (n-1)*price.erase(price.begin());
 }

I am currently doing this

if ( ret.size() == 2 ){
        order.erase(order.begin());
        quantity.erase(quantity.begin());
        price.erase(price.begin());
 }
 if ( ret.size() == 3 ){
        order.erase(order.begin());
        order.erase(order.begin());
        quantity.erase(quantity.begin());
        quantity.erase(quantity.begin());
        price.erase(price.begin());
        price.erase(price.begin());
}

Upvotes: 0

Views: 239

Answers (1)

DevSolar
DevSolar

Reputation: 70213

order.erase( order.begin(), order.begin() + ( ret.size() - 1 ) );

Needs prior checking of ret.size() vs. order.size() of course, but it seems your code can assert that from context.

That being said, when you are repeatedly erasing from the beginning of your vectors, perhaps your vectors are sorted the wrong way, or you might be better off with std::deque, performance-wise.


Edit: From the comments, it appears that your actual problem is "how to remove all but the last element of a vector". There are a number of ways to do this, like

// actually erasing all but the last
order.erase( order.begin(), order.end() - 1 );

...or...

// creating a new vector with the last element of the old
order = vector< ... >{ order.back() };

(The elipsis here standing for the type of your order vector, not the actual elipsis -- you will have to fill in that part.)

Upvotes: 2

Related Questions