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

问题描述 投票:44回答:4

这是我的交换功能:

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

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

swap(v[position], v[nextposition]); //creates errors
c++ vector swap
4个回答
99
投票

我认为你所寻找的是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

42
投票

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

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

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

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

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

试试吧:

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;
}

两次交换前两个元素:

2 1 3 4 5 6 7 8 9

21
投票

std::swap有一个<algorithm>


4
投票

在通过引用传递向量之后

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

将产生预期的结果。

© www.soinside.com 2019 - 2024. All rights reserved.