[英]Can't reverse an array with double pointer
我在學校作業中遇到了一些問題,我們應該創建自己的迭代器並使用它來反轉數組中的元素。 如果只是單指針,我想我會管理的,但這是雙指針,令人困惑……
這是反向代碼:
void reverse(T start, T end)
{
T temp = start;
while(start < end)
{
*temp = *start;
*start = *end;
*end = *temp;
++start;
--end;
}
}
這里的問題是,因為當我點temp
,以start
, temp
得到start
的價值和地址。但是,當我點start
到end
以及隨后start
和temp
的變化自然。
我一生都無法解決該問題。
這是我在主體中撥打的電話:
int a[5] = {5, 12, 1, 6, 9};
Itterfunctions<int*> itt;
int *b = a;
itt.reverse(b, b+4);
for (int i = 0; i < 5; i++)
{
cout<<a[i]<<" ";
}
我解決了!
坐在這個問題上了兩天,當我最終決定在這里發布時,我解決了。
這是這樣的:
void reverse(T start, T end)
{
unsigned temp = *start;
while(start < end)
{
temp = *start;
*start = *end;
*end = temp;
++start;
--end;
}
}
我將溫度設為無符號而不是T。但是不確定是否適用於我們自己的對象(例如我們創建的球體等)……有人知道嗎?
代替
*temp = *start;
*start = *end;
*end = temp;
采用
std::swap(*start, *end);
當前,您的臨時變量指向start
,因此您將start
位置用作臨時位置,但不是。
還要注意,通常end
不用於指向最后一個元素的迭代器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.