简体   繁体   English

反向数组 C++? 我究竟做错了什么?

[英]Reverse Array C++? What am I doing wrong?

int main(){
    int n;
    cin >> n;
    vector<int> arr(n);
    for(int i =0; i < n; i++){
       cin >> arr[i];
    }
    for(int i = n-1; n-1 >= 0; i--){
       cout << " "<< arr[i] << " ";
    }
    return 0;
} 

What am i doing wrong?我究竟做错了什么? I feel like I'm on the right track but I'm not sure whats wrong, this is the array DS problem on hacker rank.我觉得我在正确的轨道上,但我不确定什么是错的,这是黑客等级上的阵列 DS 问题。 Unfortunately i don't think they reveal the answer.不幸的是,我认为他们没有透露答案。

Change the condition to i >= 0 , There's a chance that n - 1 >= 0 might lead to an infinite loop.将条件更改为i >= 0n - 1 >= 0可能导致无限循环。 But it doesn't matter whether it does or not, because in both cases, it'll not produce the required results.但是不管它有没有,因为在这两种情况下,它都不会产生所需的结果。

for(int i = n-1; i >= 0; i--){
   std::cout << " "<< arr[i] << " ";
}

Or use, std::reverse .或者使用std::reverse

std::reverse(arr.begin(), arr.end());
for (int i = 0; i < n; i++){
    std::cout << arr[i] << " ";
}

See the second approach live here .请参阅此处的第二种方法。

for(int i = n-1; n-1 >= 0; i--){
   cout << " "<< arr[i] << " ";
}

You don't decrement n, which leads to an infinite loop, if n is <= 0.如果 n <= 0,您不减少 n,这会导致无限循环。

Don't reinvent the wheel, the Standard Library will help you here.不要重新发明轮子,标准库会在这里帮助你。
Use std::reverse :使用std::reverse

int main()
{
    std::vector<int> vec;
    int n = 0;
    int temp = 0;

    std::cin >> n;
    for (int i = 0; i != n; ++i) {
        std::cin >> temp;
        vec.emplace_back(temp);
    }

    std::reverse(std::begin(vec), std::end(vec));
}

In both the cases, you have taken the initialised the variable i=0 and incremented(in the first loop)/decremented(in the second loop) as needed.在这两种情况下,您都已初始化变量 i=0 并根据需要递增(在第一个循环中)/递减(在第二个循环中)。 However, in the second loop you have put the condition on n, despite the fact that you never change the value of n.This will lead to an infinite loop as n-1 remains constant throughout the whole program.然而,在第二个循环中,您将条件置于 n 上,尽管您从未更改 n 的值。这将导致无限循环,因为 n-1 在整个程序中保持不变。 To sort this out,you should change the condition to i-1>0 like in the code below.要解决这个问题,您应该像下面的代码一样将条件更改为 i-1>0。

for(int i = n-1; i-1 >= 0; i--)
{
   cout << " "<< arr[i] << " ";
}

Do upvote if this helps.Cheers.如果这有帮助,请点赞。干杯。

for(int i = n-1; n-1 >= 0; i--)

Here, you did a mistake with the condition of your for loop.在这里,您在for循环的条件上犯了一个错误。 You have assigned n-1 to i and in the decrements section you used i-- , So you should use a condition when the loop should be stopped or for which value of i your loop will stop.您已将n-1分配给i并且在减量部分中使用了i-- ,因此您应该使用条件何时应该停止循环或循环将停止的i值。 So, just change the condition as following:因此,只需更改条件如下:

for(int i = n-1; i >= 0; i--)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM