c++ - 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.
解决方案
在第一个块中,您应该使用:
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/
推荐阅读
- python - 如何从将多列设置为索引的数据框中获取前几行?
- python - 重置 Keras 中模型的所有权重和偏差(训练后恢复模型)
- c# - 创建文本文档时拒绝访问文档文件夹的路径
- java - JPA 强制插入相关实体(而不是更新)
- c - 如何防止程序被套接字listen()阻塞
- css - 如何让 flexbox 容器缩放我的页面?
- c - 在结构中使用点运算符与箭头运算符和字符串指针
- java - com.restApi.java.jpa.UserDaoServiceCommandLineRunner 中的字段 userDAOService 需要找不到类型为“service.UserDAOService”的 bean
- javascript - 当我尝试使用 laravel 发布表单时,控制台显示“不正确的整数值”。无法识别路由参数
- python - 切片分配的 Numpy 切片意外失败