Reputation: 8506
I'm used to program in C# or Java, so I'm doing really bad in C++. I believe it's easy but I just can't make this work. Please help me.
I have this:
void swap(vector * vet, int i, int j)
{
int temp = vet[i];
vet[i] = vet[j];
vet[j] = temp;
}
I'm calling the method this way:
swap(&vet, j, j - 1);
What I want is to pass the vector using pointers instead of using value.
Obs: The code compiles well without the "*" and "&".
Please don't say that I have to at least try to study pointers, because I did. I just can't make this damn thing work!
Upvotes: 1
Views: 1355
Reputation: 124632
Everyone has thus far responded by telling you to use references, which is correct, but they fail to explain why your code doesn't work. The problem here is that you do not understand pointer arithmetic.
Let's say we have a a pointer to 10 int
s:
// best to use a vector for this, but for the sake of example...
int *p = new int[10];
Now, if we want to change the value of the second int
in that chunk of memory we can write:
*(p + 1) = 20;
Or, the equivalent:
p[1] = 20;
See? Those two lines do the same thing. Adding n
to a pointer increases the address of the pointer by n * sizeof *p
bytes. Pointer arithmetic is convenient because it hides the sizeof
bit from you and allows you to work with logical units (elements) instead of bytes.
So, knowing that, back to your broken code:
vet[i] = vet[j];
This indexes i * sizeof *vet
bytes away from the pointer, i.e., i full vectors away from the base address. Obviously that is wrong, you wanted to invoke operator[]
on the vector, i.e., treat it as an array. It is not an array however, so the correct syntax would be:
(*vec)[i]
Or
vec->operator[](i);
That said... just use a reference. Safer (object guaranteed to be valid) and idiomatic.
Upvotes: 4
Reputation: 392833
In fact, in C++ you'd just say
using std::swap;
swap(vet[i], vet[j]);
Upvotes: 2
Reputation: 1973
You can try something like....
void swap(vector<int> &vet, int i, int j)
{
int temp = vet[i];
vet[i] = vet[j];
vet[j] = temp;
}
and call your swap function as
swap(vet,i,j);
Bottomline: Use reference variables.They are more like reference in Java.
Upvotes: 3
Reputation: 16148
You should take the vector by reference rather than "pass by pointer".
void swap(std::vector<int>& vet, std::size_t i, std::size_t j)
{
using std::swap;
swap(vet[i], vet[j]);
}
http://en.cppreference.com/w/cpp/algorithm/swap
Note the more idiomatic:
http://en.cppreference.com/w/cpp/algorithm/iter_swap
Upvotes: 5