繁体   English   中英

未知大小的二维向量

[英]2D vector of unknown size

我定义了一个空的向量向量:

vector< vector<int> > v;

我如何用大小为 2 个整数(来自输入)的向量填充该空向量,每次 while 循环迭代?

while ( cin >> x >> y ) {
  //....
}

这个能用吗? 或者最好和最优雅/最有效的方法是什么?

while ( cin >> x >> y )
{
   vector<int> row;
   row.push_back( x );
   row.push_back( y );
   v.push_back( row );
}

正如 JerryCoffin 所指出的,您可能最好使用:

struct Point {
    int x;
    int y;
};

然后你可能会重载输出运算符

std::ostream& operator<< (std::ostream& o,const Point& xy){
    o << xy.x << " " << xy.y;
    return o;
}

和类似的输入操作符(参见例如这里)。 然后你可以像这样使用它:

int main() {
    Point xy;
    std::vector<Point> v;
    v.push_back(xy);
    std::cout << v[0] << std::endl;
    return 0;
}

另一种方法是将值推送到一维向量中,然后将该一维向量推送到二维向量中。 我还打印了这些值作为测试。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t,n,temp;
    cin>>t;
    vector<vector<int>> value;
    for(int i=0;i<t;i++)
    {
        cin>>n;
        vector<int> x;
        for(int j=0;j<n;j++)
        {
            cin>>temp;
            x.push_back(temp);
        }
        value.push_back(x);
    }
    for(int i=0;i<t;i++)
    {
        for(int j=0;j<value[i].size();j++)
        {
            cout<<value[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

希望能帮助到你!!

我写了它 - 编译器没有说什么,但我从未使用过向量,所以我还没有想出如何打印它

您可以使用例如基于范围的 for 循环 (C++11) 进行打印:

for (const auto &vec : v) {     // for every vector in v
    for (const auto &num : vec) // print the numbers
        cout << num << " ";
    cout << '\n';
}

和常规 for 循环:

for (unsigned int i = 0; i != v.size(); ++i) {
    for (unsigned int j = 0; j != v[i].size(); ++j) {
        cout << v[i][j] << " ";   
    }
    cout << '\n';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM