簡體   English   中英

如何避免在基於范圍的 for 循環中使用自動說明符?

[英]How can i avoid the use of the auto specifier in range-based for loops?

我正在嘗試在下一個循環中使用自動說明符

for (auto x : graf[nod])
{
    if (cost + x.second < dist[x.first])
    {
        dist[x.first] = cost+x.second;
        pq.push(make_pair(x.first, dist[x.first]));
    }
}

其中 graf 是成對的向量,在 c++98 中似乎不起作用,我不知道如何將其變成更常見的循環。 有什么辦法可以避免嗎?

你可能會變成 C++11

for (auto x : graf[nod])

進入 C++03

for (std::size_t i = 0; i != graf[nod].size(); ++i) {
    std::pair<T1, T2> x = graf[nod][i];
    // ...
}

范圍不是魔法。 它有一個定義

for ( init-statement(optional)range_declaration : range_expression ) loop_statement

方法

{
  init - statement 
  auto&& __range = range_expression;
  auto __begin = begin_expr;
  auto __end = end_expr;
  for (; __begin != __end; ++__begin) {
    range_declaration = *__begin;
    loop_statement
  }
}

auto也不是魔術。 它只是實際類型的占位符。

話雖如此,您可以使用cppinsights.io將現代 C++ 中的一些快捷方式轉換為更傳統的概念。 例如。 這個:

#include <utility>
#include <vector>

int main() {
  std::vector<std::vector<std::pair<int, int>>> graf;

  // fill graf

  for (auto x : graf[0]) {
    x.first += x.second;
  }
}

翻譯成

#include <utility>
#include <vector>

int main()
{
  std::vector<std::vector<std::pair<int, int> > > graf = std::vector<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > >, std::allocator<std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > > >();
  {
    std::vector<std::pair<int, int>, std::allocator<std::pair<int, int> > > & __range1 = graf.operator[](0);
    std::__wrap_iter<std::pair<int, int> *> __begin1 = __range1.begin();
    std::__wrap_iter<std::pair<int, int> *> __end1 = __range1.end();
    for(; std::operator!=(__begin1, __end1); __begin1.operator++()) 
    {
      std::pair<int, int> x = std::pair<int, int>(__begin1.operator*());
      x.first += x.second;
    }

  }
}

std::__wrap_iter是一個實現細節,但除此之外很清楚發生了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM