-3

我最后有几个带数字的字符串:说: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;
}
4

1 回答 1

2

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

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;
于 2018-02-20T11:38:52.983 回答