该程序的输出说明:

时间:2018-12-10 18:51:45

标签: c++

因此,矢量中应该包含以下内容:
32,-64,-1,-1、2,-4、8,-16、32

但是,我真的不明白怎么做?有人可以解释一下吗?任何帮助表示赞赏。

vector<int>vv(3,-1);
for(; vv[0]<10; vv[1] *=-2)
{
    vv.push_back(vv[1]);
    vv[0]=vv[vv.size()-1];
}

1 个答案:

答案 0 :(得分:0)

  

解释?

Debugger是一个更好的选择,但是您可以添加cout来说明代码的进度。


// Note: -std=c++17 supports the 'using list'

#include <iostream>
using std::cout, std::cerr, std::endl, std::hex, std::dec, std::cin; // c++17

#include <vector>
using std::vector;

#include <string>
using std::string;

class T985_t // ctor and dtor are compiler provided defaults
{
public:
   int operator()() { return exec(); }  // functor entry

private: // methods

   int exec()
      {
         vector<int>vv(3,-1);
         show(vv, "\n  a ");         // ADD initial show

         for(; vv[0]<10; vv[1] *=-2)
         {
            vv.push_back(vv[1]);
            show(vv, "\n  b ");      // ADD show

          //vv[0]==vv[vv.size()-1];  warning: value computed is not used [-Wunused-value]
          // previous line causes infinite loop

            vv[0]=vv[vv.size()-1];
            show(vv, "\n  c ");      // ADD show
         }
         show(vv, "\n  d ");         // ADD final show
         return 0;
      }

   void show(vector<int>& iVec, string lbl )
      {
         cout << lbl;
         for (auto i : iVec)
            cout << i << "  ";
         cout << endl;
      }

}; // class T985_t

int main(int , char**) { return T985_t()(); }  // a functor

输出:单步执行进度,一次更改1次。

  a -1  -1  -1  

  b -1  -1  -1  -1  

  c -1  -1  -1  -1  

  b -1  2  -1  -1  2  

  c 2  2  -1  -1  2  

  b 2  -4  -1  -1  2  -4  

  c -4  -4  -1  -1  2  -4  

  b -4  8  -1  -1  2  -4  8  

  c 8  8  -1  -1  2  -4  8  

  b 8  -16  -1  -1  2  -4  8  -16  

  c -16  -16  -1  -1  2  -4  8  -16  

  b -16  32  -1  -1  2  -4  8  -16  32  

  c 32  32  -1  -1  2  -4  8  -16  32  

  d 32  -64  -1  -1  2  -4  8  -16  32