简体   繁体   English

C ++:交换两个不同向量的两个元素

[英]C++: Swap two elements of two different vectors

std::vector<int> v1 = {1,3,6};
std::vector<int> v2 = {2,4,7};

swap v1[m] with v2[n] 用v2 [n]交换v1 [m]

instead of copying and then just overwriting both elements 而不是复制然后覆盖两个元素

I tried 我试过了

std::swap(v1.begin() + m, v2.begin() + n);

but that didn't work 但这没用

std::swap需要引用,而不是迭代器:

std::swap(v1[m], v2[n]);

您对此太想了-您只需要:

std::swap(  v1[m],  v2[n] );

From your example it looks like what you need might be iter_swap 从您的示例看来,您可能需要的是iter_swap

As per your example: 根据您的示例:

std::iter_swap(v1.begin() + m, v2.begin() + n);

Should work for you. 应该为您工作。

You can of course use iterators with swap : 您当然可以将迭代器与swap一起使用:

std::swap(*(v1.begin() + m), *(v2.begin() + n));

or 要么

std::swap(v1[m], v2[n]);

or 要么

std::swap(v1.at(m), v2.at(n));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM