【发布时间】:2013-06-10 04:15:16
【问题描述】:
我使用 Visual Studio 2012。我创建了自己的函数,其工作原理类似于 sprintf(&a)。
我需要解决一个问题:如何交换两个特定的指针元素?
这是我的代码:
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
void swap_spec(vector<int>* a, vector<int>* b)
{
vector<int>* tmp = NULL;
*tmp = *a;
*a = *b;
*b = *tmp;
}
int main()
{
vector<int> test(4);
test[0] = 5;
test[1] = 4;
test[2] = 3;
test[3] = 2;
swap_spec(*test[0], *test[1]);
printf("%d %d", test[0], test[1]);
return 0;
}
我遇到了一个错误:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
怎么了?我应该改变什么?
【问题讨论】:
-
vector<int>* tmp = NULL; *tmp = *a;你认为这是做什么的?尤其是*tmp部分? -
您的
swap_spec()函数需要指向向量的指针,但您传递了....其他东西。我什至不确定你打算通过什么。看起来您尝试将指针传递给向量的各个元素。 -
std::swap有什么问题? -
@chris -> 交换(&abc[0], &abc[1]);很多错误:) swap(abc[0], abc[1]); -> 段错误
-
@Luchian Grigore 矢量
* tmp = NULL; -> 避免编译器警告未使用的 tmp;
标签: c++ pointers vector key-value