C++ 试图交换向量中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6224830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:43:02  来源:igfitidea点击:

C++ trying to swap values in a vector

c++vectorswap

提问by user782311

This is my swap function:

这是我的交换功能:

template <typename t>
void swap (t& x, t& y)
{
    t temp = x;
    x = y;
    y = temp;
    return;
}

And this is my function (on a side note v stores strings) call to swap values but whenever I try to call using values in a vector I get an error. I'm not sure what I'm doing wrong.

这是我的函数(在旁注中 v 存储字符串)调用交换值,但是每当我尝试使用向量中的值调用时,我都会收到错误消息。我不确定我做错了什么。

swap(v[position], v[nextposition]); //creates errors

回答by Moha the almighty camel

I think what you are looking for is iter_swapwhich you can find also in <algorithm>.
all you need to do is just pass two iterators each pointing at one of the elements you want to exchange.
since you have the position of the two elements, you can do something like this:

我认为您正在寻找的是iter_swap您也可以在 <algorithm>.
您需要做的就是传递两个迭代器,每个迭代器都指向您要交换的元素之一。
由于您拥有两个元素的位置,因此您可以执行以下操作:

// assuming your vector is called v
iter_swap(v.begin() + position, v.begin() + next_position);
// position, next_position are the indices of the elements you want to swap

回答by linse

Both proposed possibilities (std::swapand std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0]and v[1].

两种提议的可能性 (std::swapstd::iter_swap) 都有效,只是语法略有不同。让我们交换一个向量的第一个和第二个元素,v[0]v[1]

We can swap based on the objects contents:

我们可以根据对象内容进行交换:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

或者基于底层迭代器进行交换:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

尝试一下:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

两次交换前两个元素:

2 1 3 4 5 6 7 8 9

回答by ólafur Waage

There is a std::swapin <algorithm>

有一个std::swap<algorithm>

回答by faro_hf

after passing the vector by reference

通过引用传递向量后

swap(vector[position],vector[otherPosition]);

will produce the expected result.

将产生预期的结果。