c++ - How do I print an entire vector?
问题描述
I want all items in the vector "listofnums" to print. I tried putting "cout << listofnums[i]" within the for loop thinking it would print each item as it iterated and that didn't work. Putting the cout outside of the loop hasn't worked for me either.
#include <iostream>
#include <vector>
using namespace std;
int main(){
//variables
int a, b, i = 0; // a & b inputs, i for iterating
int likedigits = 0; //counts the number of like digits
//entering number range
cout << "Enter the first number" << endl;
cin >> a;
cout << "Enter the second number" << endl;
cin >> b;
//making a vector to contain numbers between a and b
vector<int> listofnums((b-a)+1);
for (i <= (b-a); i++;) {
int initialvalue = a;
listofnums[i] = initialvalue;
initialvalue++;
}
cout << listofnums << endl;
return 0;
}
解决方案
对于初学者来说,for 语句
for (i <= (b-a); i++;) {
写错了。你的意思是
for ( ;i <= (b-a); i++) {
在这个(更新的)for循环中
for ( ;i <= (b-a); i++) {
int initialvalue = a;
listofnums[i] = initialvalue;
initialvalue++;
}
向量的所有元素都具有值 a,因为变量initialvalue
是在每次迭代中定义的。将变量的声明放在 , 循环之外。
int initialvalue = a;
for (i <= (b-a); i++;) {
listofnums[i] = initialvalue;
initialvalue++;
}
要输出向量,您可以使用例如基于范围的 for 循环
for ( const auto &item : listofnums )
{
std::cout << item << ' ';
}
std::cout << '\n';
这是一个演示程序。
#include <iostream>
#include <tuple>
#include <vector>
#include <algorithm>
int main()
{
int a = 0, b = 0;
std::cout << "Enter the first number: ";
std::cin >> a;
std::cout << "Enter the second number: ";
std::cin >> b;
std::tie( a, b ) = std::minmax( { a, b } );
std::vector<int> listofnums( b - a + 1 );
int initialvalue = a;
for ( auto &item : listofnums ) item = initialvalue++;
for ( const auto &item : listofnums )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
它的输出可能如下所示
Enter the first number: 10
Enter the second number: 5
5 6 7 8 9 10
推荐阅读
- vb.net - 需要帮助获取 MAX ID 并在 ExecuteReader 上填写数据和错误
- php - 如何在 Laravel 中显示注册用户数?
- haskell - 为什么在 'do{ let{ the= Just "Hi!"}; 中输出 'Nothing' _ <- 序列 [the,Nothing]; 纯粹的“不可能!” }'
- anylogic - 在物流模型中上传时间数据集
- javascript - 为什么我的 javascript 代码中的变量不起作用?
- php - 使用 http_build_query 时,如何将 '%2' 替换为 '+'?
- scala - 将 spark 数据框列值替换为随机值(例如 UUID)
- android - 由于 jenkins 触发的 aws 实例上未接受某些许可证,因此无法安装以下 Android SDK 包
- python - 不明白“while not”循环是如何工作的
- c++ - StringCch* 函数和 Cstring