【问题标题】:How to create 2D string vector and insert Data in it?如何创建二维字符串向量并在其中插入数据?
【发布时间】:2018-02-20 10:29:09
【问题描述】:

我最后有几个带数字的字符串: 说:abc_0_0 xyz_1_0 dfg_0_1 asd_2_0 ghj_0_2 iop_2_1 hkk_1_1 asv_2_2 我可以一次读取一次,根据最后的数字,我需要创建一个二维向量并将字符串元素插入到数字给定的索引处。

因此,对于给定的字符串:索引 [0][0] 应该有 abc,索引 [1][0] 应该有 xyz,索引 [0] [1] 应该有 dfg,索引 [2][0] 应该有 asd,索引 [0][2] 应该有 ghj,索引 [2][1] 应该有 iop,索引 [1][1] 应该有 hkk,索引 [2][2] 应该有 asv。

如何实现?不知道vector的实现

#include <cstring>
#include <string>
#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    int maxentry;
    vector <vector <string>> Data;
    string s;
    char a;
    int c,d;
    cin >> maxentry;
    for(int j=0; j<maxentry; j++)
    {
        cin >> s;
        a=s[4];
        cout << s[4] << endl;
        cout << a <<endl;
        c = int (s[4])-int ('0');
        d = int (s[6])-int ('0');
        cout<< "Value: " <<c << " " << d << endl;
        Data[c][d]=s;  //Doesn't work here
    }



    return 0;
}

【问题讨论】:

  • 到目前为止你实现了什么?
  • 如何实现?您创建一个 2d 字符串向量并将数据插入其中......这个问题还不清楚。请提供minimal reproducible example
  • @MarekChocholáček 希望这有助于更好地理解这个问题!
  • @user463035818 我不知道向量的实现。我只是一个初学者。

标签: c++ 2d-vector


【解决方案1】:

您的问题是 std::vector 是动态结构,这意味着它会改变大小。调用向量的默认构造函数后,其大小为 0。这意味着您的二维数组为空。一种可能的实现是,只要您没有足够的空间存放相应的索引,您就可以resize它:

for(int j=0; j<maxentry; j++)
{
    // ...
    c = int (s[4])-int ('0');
    d = int (s[6])-int ('0');
    if (Data.size() <= c)
        Data.resize(c + 1); // not enough space -> resize needed
    if (Data[c].size() <= d )
        Data[c].resize(d + 1); // not enough space -> resize needed
    // ...
}

如果您不想调整大小并且知道不需要比 10x10 更大的二维数组,您可以改用 std::array

array< array< string, 10 >, 10 > Data;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多