【问题标题】:How would one push back an empty vector of pairs to another vector?如何将一对空向量推回另一个向量?
【发布时间】:2013-04-26 00:24:39
【问题描述】:
  std::vector<std::vector< std::pair<int, int> > > offset_table;
  for (int i = 0; i < (offset.Width()*offset.Width()); ++i)
  {
    offset_table.push_back(  std::vector< std::pair<int, int> >  );
  }

这是我的代码,但出现错误:

main.cpp: In function ‘void Compress(const Image<Color>&, Image<bool>&, Image<Color>&, Image<Offset>&)’:
main.cpp:48:66: error: expected primary-expression before ‘)’ token

我不想要成对中的任何值,我现在只想拥有一个空向量的向量。我该怎么做?

【问题讨论】:

    标签: c++ vector std-pair push-back


    【解决方案1】:

    您想构造一个向量以传递给 push_back,而您只是缺少括号:

    offset_table.push_back(  std::vector< std::pair<int, int> >()  );
    

    或者,您可以执行以下操作,而不是循环。更好的是,向量将在一次分配中分配恰到好处的内存量:

    offset_table.resize( offset.Width()*offset.Width(), std::vector< std::pair<int, int> >() );
    

    或者这个更简洁,因为它使用了调整大小的默认第二个参数:

    offset_table.resize( offset.Width()*offset.Width() );
    

    【讨论】:

      【解决方案2】:
      std::vector<std::vector< std::pair<int, int> > > offset_table;
      

      这是一个二维数组,所以你需要使用嵌套数组。仅用于获取内部向量的长度。

      for(vector< pair<int, int >> vv in offset_table)
      {
          if(vv.size() == 0)
          {
              // this is your target.
          }
      }
      

      【讨论】:

      • 我认为您误解了这个问题。我认为问题是如何将空向量推回向量向量。
      猜你喜欢
      • 2020-07-18
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多