c++ - 如何打印整个 vector ?

标签 c++ loops for-loop vector printing

我希望打印“listofnums” vector 中的所有项目。我尝试将“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++;                                               
}

vector 的所有元素都具有a值,因为在每次迭代中都定义了initialvalue变量。将变量的声明放置在循环之外。
   int initialvalue = a;
   for (i <= (b-a); i++;) {  
        listofnums[i] = initialvalue;                                 
        initialvalue++;                                               
    }

要输出 vector ,您可以使用例如基于范围的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 

关于c++ - 如何打印整个 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60028384/

相关文章:

java - Python 中的 OOP 范式

c++ - Qt 程序在另一台计算机上执行时崩溃

c++ - C/C++ - 检查今天是否是本月的第一个星期一

java - 使用字符串数组中数据的更快方法?

r - (R) 数据帧的 for 循环不起作用

JavaScript 替代 "for each"循环

头文件中的 C++ 模板

Java 条件困惑? (初学者)

python - itertools 使用列表进行计数

r - 在第一个非 NA 值之后递归填充元素