I have a vector c(9,6,3,4,2,1,5,7,8)
, and I want to switch the elements at index 2 and at index 5 in the vector. However, I don't want to have to create a temporary variable and would like to make the switch in one call. How would I do that?
swap(B) and swaps the contents. The std::vector::swap function exchanges the contents of one vector with another. It swaps the addresses(i.e. the containers exchange references to their data) of two vectors rather than swapping each element one by one which is done in constant time O(1).
To swap two vectors, you need only swap each of these members. By swapping the pointers, this vector will point to the other vector's data on the free store and the other will point to this one's data.
vector::swap() This function is used to swap the contents of one vector with another vector of same type and sizes of vectors may differ.
How about just x[c(i,j)] <- x[c(j,i)]
? Similar to replace(...)
, but perhaps a bit simpler.
swtch <- function(x,i,j) {x[c(i,j)] <- x[c(j,i)]; x}
swtch(c(9,6,3,4,2,1,5,7,8) , 2,5)
# [1] 9 2 3 4 6 1 5 7 8
You could use replace()
.
x <- c(9, 6, 3, 4, 2, 1, 5, 7, 8)
replace(x, c(2, 5), x[c(5, 2)])
# [1] 9 2 3 4 6 1 5 7 8
And if you don't even want to assign x
, you can use
replace(
c(9, 6, 3, 4, 2, 1, 5, 7, 8),
c(2, 5),
c(9, 6, 3, 4, 2, 1, 5, 7, 8)[c(5, 2)]
)
# [1] 9 2 3 4 6 1 5 7 8
but that's a bit silly. You will probably want x
assigned to begin with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With