Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用push_-back打印矢量阵列_C++_Arrays_Loops_C++11_Vector - Fatal编程技术网

C++ 使用push_-back打印矢量阵列

C++ 使用push_-back打印矢量阵列,c++,arrays,loops,c++11,vector,C++,Arrays,Loops,C++11,Vector,我试图使用vector和for range循环显示动态数组输入的值,但当它打印时,显示的是0,然后是输入的值 请不要介意if语句,因为我在测试时使用了较小的样本量。但是如果我输入大小,比如说它的3,那么输入值,比如1,2,3,输出将是0 1 2 3。我正在尝试删除前三个0 int main() { std::cout << "How many numerical values do you wish to enter: "; int values, index, co

我试图使用vector和for range循环显示动态数组输入的值,但当它打印时,显示的是0,然后是输入的值

请不要介意if语句,因为我在测试时使用了较小的样本量。但是如果我输入大小,比如说它的3,那么输入值,比如1,2,3,输出将是0 1 2 3。我正在尝试删除前三个0

int main()
{
    std::cout << "How many numerical values do you wish to enter: ";
    int values, index, collect;
    std::cin >> values;
    std::vector<int> numbers(values);
    //if(values == 31)
    //{
        for (index = 0; index < values; index++)
        {
            std::cout << "Enter value[" << (index + 1) << "]: ";
            std::cin >> collect;
            numbers.push_back(collect);
        }
        for (auto &showNumbers : numbers)
        {
            std::cout << showNumbers << " ";
        }
    //}

    return 0;
}
intmain()
{
std::cout>值;
std::向量数(值);
//如果(值==31)
//{
对于(索引=0;索引<值;索引++)
{

std::cout此行创建
值的向量

std::vector<int> numbers(values);
你可以:

  • std::vector number(值);
    替换为
    std::vector number;
    (这将创建空向量),或
  • 替换
    数字。用
    数字向后推(收集);
    。在(索引)=收集;
    (这将设置元素值)

  • 只要做一次收集,你就很好了。你甚至可以尝试一下这个数字索引;
    你正在使用一个构造函数

    std::vector<int> numbers(values);
    
    std::向量数(值);
    
    就你而言:

    数值=3

    它将前3个内容设置为零。然后使用push_back进一步添加值。您必须将向量声明为:

    std::vector<int> numbers;
    
    std::向量数;
    
    使用std::vector number;当您添加(值)时,您将创建一个零向量,请阅读一些文档:感谢您的解释和答案。
    std::vector<int> numbers;