c++ - 我写了一个 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});
}
解决方案
推荐阅读
- flutter - 如何在 Dart 中声明 final 类以防止从它扩展?
- c++ - 读取文件并将数据存储在地图中
> C++98 - python - Django DefaultRouter 和 ViewSets 问题
- mysql - 如何解决 VB.net 中的此类错误?MySql.Data.MySqlClient.MySqlException: '你的 Sql 语法有错误;看说明书……”
- r - 如何从 R 中的数据集计算通货膨胀率和失业率
- javascript - 以 1 x 1 加载 iframe
- python - 任何用于最佳(最精确)字符串匹配的内置 Python 库或函数,如路由表?如果不是,我的代码是最有效的吗?
- c++ - Windows 上的 Mongocxx 问题
- php - 带有 WooCommerce 身份验证的 WordPress 自定义 API
- ios - 如何快速检查从 MDCTabBarView 中选择了哪个选项卡