带向量的反向输出数字(C++)

Output numbers in reverse (C++) w/ vectors

我第一次因为这个 class 而被困在实验室里。请帮忙!

提示是: 编写一个程序,读取整数列表,并反向输出这些整数。输入以一个整数开头,表示后面的整数个数。为简化编码,在每个输出整数后跟一个逗号,包括最后一个。
例如:如果输入是:
5 2 4 6 8 10
输出是:
10,8,6,4,2,

2个问题:(1)为什么除非包含const int,否则vector不接受用户输入? (2) 为什么代码一般不起作用?好像可以正常输出,但是有错误,而且不包含结束行?

#include <iostream>
#include <vector>   
using namespace std;

int main() {
   const int MAX_ELEMENTS = 20;
   vector<int> userInts(MAX_ELEMENTS);
   unsigned int i;
   int numInts;
   
   cin >> numInts;
   
   for (i = 0; i < numInts; ++i) {
      cin >> userInts.at(i);
   }
   
   for (i = (numInts - 1); i >= 0; --i) {
      cout << userInts.at(i) << ",";
   }

   cout << endl;

   return 0;
}

unsigned int i; 条件 i >= 0 始终为真。最终您将访问一个 out-of-range 元素,该元素将抛出 std::out_of_range.

回答你的其他问题

  std::vector userInts;

创建一个没有条目的向量

 userInts.at(i)

尝试访问(不存在的)第 i 个条目。

你有2个选择

  • 创建包含大量空元素的向量
  • 要求向量动态增长

第一个就是你做的

 const int MAX_ELEMENTS = 20;
 vector<int> userInts(MAX_ELEMENTS);

或者你也可以

 userInts.push_back(x);

这将确保向量中有足够的 space 并将新元素添加到末尾。

首先,您需要指定大小,因为您没有使用 vectorpush_back 功能。由于您只使用 at,您必须提前指定大小。现在,有几种方法可以做到这一点。

示例 1:

cin >> numInts;
vector<int> userInts(numInts); // set the size AFTER the user specifies it
   
for (i = 0; i < numInts; ++i) {
   cin >> userInts.at(i);
}

或者,使用 push_back 您可以:

vector<int> userInts; // set the size AFTER the user specifies it
   
for (i = 0; i < numInts; ++i) {
   int t;
   cin >> t;
   userInts.push_back(t);
}

至于向后循环,i >= 0 对于无符号数将始终为真。相反,您可以使用迭代器。

for ( auto itr = userInts.rbegin(); itr != userInts.rend(); ++itr ) {
    cout << *itr;
}

如果您需要为反向循环使用索引,您可以这样做:

for ( i = numInts - 1; i != ~0; --i ) { // ~0 means "not 0", and is the maximum value, I believe this requires c++17 or 20 though
    cout << userInts.at(i);
}