【问题标题】:why c++ std accumulate is always return 0为什么 c++ std 累积总是返回 0
【发布时间】:2019-03-10 12:37:09
【问题描述】:

我正在尝试使用 c++ 对输入中的 3 个整数求和,但我一直得到 0。请帮助 thx。

  vector<int> x;
  x.reserve(3);
  cin >> x[0] >> x[1] >> x[2];
  int sum = std::accumulate(x.begin(), x.end(), 0);
  cout << sum << endl;
  return 0;

1

2

3

0

【问题讨论】:

  • cin &gt;&gt; x[0] &gt;&gt; x[1] &gt;&gt; x[2] 具有未定义的行为,因为 x.size() 为零。一旦行为未定义,所有程序的任何行为都将被取消。使用x.resize(3) 而不是x.reserve(3)。所有x.reserve(3) 所做的就是避免在调整13 之间的新大小时重新分配大小。它不会自行调整大小。
  • 我这里有固定代码:ideone.com/7587E6
  • 好的提交,但一般来说,它应该编译。考虑到这一点,因为“多少 int”很少是固定的,您更有可能想要“即时”计算有多少输入。所以也许使用一个循环,cin 到一个本地 var,然后 x.push_back(a_local_var),并重复直到某些条件(可能是 eof(),或本地 var == -1 等)x.size() 是你的计数器.
  • 感谢您的帮助。现在我明白容量和大小的区别了。

标签: c++ vector iterator accumulate


【解决方案1】:

vector::reserve(size_type n) 将请求改变向量的容量,而不是大小。你可以使用resize函数,甚至更好的构造函数。

int main()
{
    std::vector<int> x(3,0);  //set the size to 3 and fill with zeros.

    std::cin >> x[0] >> x[1] >> x[2];

    int sum = std::accumulate(x.begin(), x.end(), 0);
    std::cout << sum << std::endl;
}

您可以阅读此答案here,了解保留与调整大小之间的区别。

【讨论】:

    【解决方案2】:

    先用一些东西填充你的向量,否则你可能会得到未定义的东西

    vector<int> x(3,0);
    

    【讨论】:

      【解决方案3】:

      使用 c++ 对输入中的 3 个整数求和 为什么累积总是返回 0

      这个答案使用push_back(),不需要知道输入了多少整数,因为向量会自动展开;通过这种方式,它回避了使您的代码失效的 std::vector 问题。

      考虑一下,因为“多少 int”可能被提交很少是固定的,您更有可能想要“即时”计算有多少输入。所以也许使用一个循环,cin 到一个本地 var,然后 x.push_back(a_local_var),并重复直到某些条件(可能是 eof(),或本地 var == -1 等)x.size() 是你的计数器.

      这是一个功能示例,使用命令行 vars 和 eof()(以及向量和累积)。

       // Note: compile with -std=c++17 for the using comma list
       #include <iostream>
       using std::cout, std::cerr, std::endl, std::hex, std::dec, std::cin, std::flush; // c++17
      
       #include <vector>
       using std::vector;
      
       #include <string>
       using std::string;
      
       #include <sstream>
       using std::stringstream;
      
       #include <numeric>
       using std::accumulate;
      
       #include <cassert>
      
      
       class T951_t // ctor and dtor compiler provided defaults
       {
       public:
          int operator()(int argc, char* argv[]) { return exec(argc, argv); } // functor entry
      
       private:
      
          stringstream ssIn; // to simulate user input
      
          int exec(int argc, char* argv[])
             {
                int retVal = initTest(argc, argv); // transfer command line strings into ssIn
                if(retVal != 0) return retVal;
      
                // ------------------------------------------------------------
                // simulate unknown quantity of ints
      
                vector<int> x;
      
                do {
                   int localInt = 0;
                   ssIn >> localInt;
      
                   if(!ssIn.good())  // was transfer ok?
                   {                 // no
                      if (ssIn.eof()) break; // but we tolerate eof
                      // else err and exit
                      cerr << "\n  !ssIn.good() failure after int value " 
                           << x.back() << endl;
                      assert(0);  // harsh - user typo stops test
                   }
                   x.push_back(localInt); // yes transfer is ok, put int into vector
      
                   //cout << "\n  " << localInt;  // diagnostic
                } while(true);
      
                showResults(x);
      
                return 0;
             }
      
          // this test uses a stringstream (ssIn) to deliver input to the app
          // ssIn is initialized from the command line arguments
          int initTest(int argc, char* argv[])
             {
                if (argc < 2) {
                   cerr << "\n  integer input required" << endl;
                   return -1;
                }
                // test init
                for (int i=1; i < argc; ++i) {
                   // cout << "\n  " << argv[i]; // diagnostic
                   ssIn   << argv[i] << " ";     // user text into stream
                }
                cout << endl;
                return 0;
             }
      
          // display size and contents of vector x
          void showResults(vector<int> x)
             {
                cout << "\n  x.size(): " << x.size() << endl;
      
                int sum = std::accumulate(x.begin(), x.end(), 0);
      
                for (auto i : x)
                   cout << "  " << i;
                cout << endl;
      
                cout << "\n  sums to: " << sum << '\n' << endl;
             }
      
      
       }; // class T951_t
      
      
        int main(int argc, char* argv[]) { return T951_t()(argc, argv); } // call functor
      

      测试:

      ./dumy951 1 2 3 55 12345678900

      ./dumy951 1 2 3 y 55 12345678900

      ./dumy951 1 2 3 4 5 6 7 8 9 10

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-24
        • 2016-09-16
        • 2020-05-25
        • 2013-02-26
        • 2013-06-25
        • 1970-01-01
        • 2013-02-14
        相关资源
        最近更新 更多