这是我的交换功能:
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)
小智 43
两种提议的可能性(std::swap和std::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)
小智 5
通过引用传递向量后
swap(vector[position],vector[otherPosition]);
Run Code Online (Sandbox Code Playgroud)
将产生预期的结果。