C++ 为什么我能';t将int写入向量
我的意见是:C++ 为什么我能';t将int写入向量,c++,vector,C++,Vector,我的意见是: 4 4 4 8 7 3 2 5 9 3 6 3 2 5 4 4 1 6 一个计划是: #include <iostream> #include <vector> int main () { int rows, columns; std::cin >> rows >> columns; std::vector<int> map(rows); int cell; for (int row =
4 4
4 8 7 3
2 5 9 3
6 3 2 5
4 4 1 6
一个计划是:
#include <iostream>
#include <vector>
int main () {
int rows, columns;
std::cin >> rows >> columns;
std::vector<int> map(rows);
int cell;
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
std::cin >> cell;
map[row].push_back(cell);
}
}
}
我不明白为什么会发生这种情况?替换std::vector map(行)代码>带有
std::vector< std::vector<int> > map(rows);
std::vectormap(行);
std::向量映射(行)
:map是一个包含行
元素的向量,map[row]
的类型是一个int
,因此不能对其应用推回
std::vectormap(行)
:map是一个包含行
元素的向量向量,type ofmap[row]
是向量
,您可以对其应用推回
。在这一行中
std::vector<int> map(rows);
std::向量映射(行);
您可以使用长度行声明整数向量。正如我从你的代码中了解到的,你需要一个向量的向量。也许你需要像这样的东西
int rows, columns;
std::cin >> rows >> columns;
std::vector<std::vector<int>> map(rows);
int cell;
for (int row = 0; row < rows; ++row) {
map[row].resize(columns);
for (int column = 0; column < columns; ++column) {
std::cin >> cell;
map[row][column] = cell;
}
}
int行、列;
std::cin>>行>>列;
std::矢量图(行);
int细胞;
对于(int行=0;行<行;++行){
映射[行]。调整大小(列);
for(int列=0;列<列;++列){
std::cin>>细胞;
映射[行][列]=单元格;
}
}
事实上,您将拥有一个二维表格。但是,您仅定义了“行”:
std::向量映射(行);
这是一个整数序列的向量
你必须定义一个整数向量的向量
代码可以如下所示
#include <ostream>
#include <vector>
int main ()
{
int rows, columns;
std::cin >> rows >> columns;
std::vector<std::vector<int>> map;
map.reserve( rows );
for ( int row = 0; row < rows; ++row )
{
std::vector<int> tmp;
tmp.reserve( columns );
for ( int column = 0; column < columns; ++column )
{
int cell;
std::cin >> cell;
tmp.push_back( cell );
}
map.push_back( tmp );
}
}
#包括
#包括
int main()
{
int行、列;
std::cin>>行>>列;
std::矢量地图;
地图.保留地(行);
对于(int行=0;行<行;++行)
{
std::载体tmp;
tmp.储备(列);
for(int列=0;列<列;++列)
{
int细胞;
std::cin>>细胞;
tmp.推回(单元);
}
地图。推回(tmp);
}
}
我认为您不希望在外部循环中调用resize()
,或者可能打算调用reserve()
或保留
而不是调整大小
?@高炉,@Mohit Jain在这种情况下保留
和调整大小
之间有什么区别?它们都将向量调整到所需的大小。@Mohit Jain在我的代码map[row]
中是std::vector
,而cell
是int
。因此,我将newint
推回到vectormap[row]
@kvorbiev:如果调用resize
它会构造很多元素,随后调用push\u back
会添加额外的元素。@πάνταῥεῖ <代码>映射声明为整数的向量
。在整数的向量中,无法向后推std::vector
。
std::vector<int> map(rows);
#include <ostream>
#include <vector>
int main ()
{
int rows, columns;
std::cin >> rows >> columns;
std::vector<std::vector<int>> map;
map.reserve( rows );
for ( int row = 0; row < rows; ++row )
{
std::vector<int> tmp;
tmp.reserve( columns );
for ( int column = 0; column < columns; ++column )
{
int cell;
std::cin >> cell;
tmp.push_back( cell );
}
map.push_back( tmp );
}
}