首页 > 解决方案 > 我写了一个 for 循环,它从 i=n-1 到 i=0 以相反的顺序进行,在其中我调用了一个向量 ans2 但向量的顺序相反,为什么?

问题描述

在这部分代码中,为什么我为 ans2 执行 push_back 它是按相反的顺序执行的。我所知道的是,当您推回向量时,它从 0 索引开始,然后将元素添加到 1,依此类推,但在这里它以相反的方式进行,即在 n-1 索引中添加第一个元素,最后添加到索引 0

vector<int>ans2;
    stack<pair<int,int>>st2;
    for (int i = n-1; i>=0; i--)
    {
        if (st2.empty())
        {
            ans2.push_back(-1);
        }
        else if (!st2.empty() && q[i]>st2.top().first)
        {
            ans2.push_back(st2.top().second);
        }
        else if (!st2.empty() && q[i]<=st2.top().first)
        {
            while (!st2.empty() && q[i]<=st2.top().first)
            {
                st2.pop();
            }
            if (st2.empty())
            {
                ans2.push_back(-1);
            }
            else if (q[i]>st2.top().first)
            {
                ans2.push_back(st2.top().second);
            }
            
        }
        st2.push({q[i],i});
        
    }

标签: c++vectorstack

解决方案


推荐阅读