如何打印整个矢量?
How do I print an entire vector?
我希望打印向量"listofnums"中的所有项目。我尝试将"cout <<listofnums[i]"放在 for 循环中,以为它会在迭代时打印每个项目,但这不起作用。把cout放在循环之外对我也不起作用。
#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
它现在可以工作了 - 根据莫斯科的弗拉德的建议,并将第一个 for 循环更改为 while 循环:
#include <iostream>
#include <vector>
using namespace std;
int main(){
//variables
int a, b, i = 0; // a & b inputs, i for iterating
//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);
int initialvalue = a;
while (i <= (b-a)) {
listofnums[i] = initialvalue;
initialvalue++;
i++;
}
for ( const auto &item : listofnums ){
std::cout << item << ' ';
}
std::cout << 'n';
return 0;
}
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- 使用rapidxml进行读取和打印.打印多个同级C++时出现问题
- 防止在打印C++打印中打印标志