首页 > 解决方案 > Problem with understanding a vector initialization

问题描述

This might be a dumb question but there is something I can't quite understand. When using a vector, whenever I want to 'push_back' an element to a certain position I can do that only if I initialize the vector in a certain way.

For example when I use this initialization:

std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}

I receive the following error: request for member 'push_back' in 'Myvec.std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)i))', which is of non-class type '__gnu_cxx::__alloc_traits >::value_type {aka int}'|

But when I use the following initialization it works:

int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec[size];

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}

I don't have any problem using it and can implement it in all sorts of tasks, but it's bugging me because I'm not sure why it is actually working. Thank you for your help in advance.

标签: c++vector

解决方案


在第一个块中,您应该使用:

std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec.push_back(x);
}

或者您可以使用:

int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec(size);
for(int i = 0; i < size; i++)
{
    cin>>Myvec[i];
}

并使用以下方法打印矢量:

for(int i = 0; i < size; i++) {
     std::cout<< Myvec[i]<<" ";
}

当您使用向量 Myvec[size] 对其进行初始化时,它会变成大小为“size”的向量的向量,这意味着每个 Myvec[i] 都是一个可以在其中推送元素的向量。

在此处阅读更多信息:https ://www.geeksforgeeks.org/2d-vector-in-cpp-with-user-defined-size/


推荐阅读