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

use*_*311 47 c++ swap vector

这是我的交换功能:

template <typename t>
void swap (t& x, t& y)
{
    t temp = x;
    x = y;
    y = temp;
    return;
}
Run Code Online (Sandbox Code Playgroud)

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

swap(v[position], v[nextposition]); //creates errors
Run Code Online (Sandbox Code Playgroud)

Moh*_*mel 101

我认为您正在寻找的是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
Run Code Online (Sandbox Code Playgroud)

  • 我有同样的问题,并且有很多答案推荐std :: swap(就像这里最高的投票一样)但是std :: swap不能(直接)交换向量的两个元素的内容.你的答案,用std :: iter_swap做的. (7认同)
  • 请注意,std :: iter_swap(it1,it2)等效于std :: swap(*it1,*it2). (5认同)
  • @latreides您能否说明“ std :: swap无法(直接)交换向量的两个元素的内容”是什么意思? (2认同)

小智 43

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

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

std::swap(v[0],v[1]);
Run Code Online (Sandbox Code Playgroud)

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

std::iter_swap(v.begin(),v.begin()+1);
Run Code Online (Sandbox Code Playgroud)

试试吧:

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;
}
Run Code Online (Sandbox Code Playgroud)

两次交换前两个元素:

2 1 3 4 5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)

  • @Mar 正如 Superfly 所建议的:请注意 std::iter_swap(it1, it2) 相当于 std::swap(*it1, *it2)。所以 std::swap 可以正常工作。 (2认同)

Óla*_*age 21

有一个std::swap<algorithm>

  • ...用于交换 2 个独立向量的内容! (2认同)

小智 5

通过引用传递向量后

swap(vector[position],vector[otherPosition]);
Run Code Online (Sandbox Code Playgroud)

将产生预期的结果。