почему накопление c ++ std всегда возвращает 0 - PullRequest
0 голосов
/ 10 марта 2019

Я пытаюсь использовать 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

Ответы [ 3 ]

1 голос
/ 10 марта 2019

vector::reserve(size_type n) запросит изменение емкости вектора, а не размера. Вы можете использовать функцию изменения размера или, что еще лучше, конструктор.

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;
}

Вы можете прочитать этот ответ здесь для различий между резервным и изменяемым размером.

0 голосов
/ 10 марта 2019

используйте 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 12 3 55 12345678900 <- ошибка после 55, потому что последнее значение int слишком большое </p>

. / Dumy951 1 2 3 y 55 12345678900 <- ошибка после значения int 3 (недопустимое значение int) </p>

. /dumy951 1 2 3 4 5 6 7 8 9 10 <- успех, результат 55 </p>

0 голосов
/ 10 марта 2019

Сначала заполните вектор чем-нибудь, если нет, вы, вероятно, получите undefined

vector<int> x(3,0);
...