在C++应用程序的使用中,需要对数组、向量和映射进行澄清

Clarification required regarding Arrays, Vectors and Maps in usage of a C++ Application

本文关键字:向量 数组 映射 应用程序 C++      更新时间:2023-10-16

我想知道适用于我的应用程序的正确算法和容器类。我正在尝试构建一个客户端-服务器通信系统,其中服务器包含一组文件(.txt)。文件结构(原型)如下:

CCD_ 1。CCD_ 2的内容也是CCD_。因此,我想做的是,当服务器应用程序启动时,它必须逐个加载这些文件,并将每个文件的内容保存在Container类中,然后再次将文件的内容基于分隔符(即)保存到特定的变量中

for (int i=0; i< (Number of files); i++) 
{
1) Load the file[0] in Container class[0];
2) Read the Container class[0] search for occurences of delimiters "_" and "|"
3) Till next "|" occurs, save the value occurred at "_" to an array or variable (save it in a buffer)
4) Do this till the file length completes or reaches EOF
5) Next read the second file, save it in Container class[1] and follow the steps as in 2),3) and 4)
}

我想知道Vector还是Map适合我的要求?因为我需要搜索分隔符和push_back的出现,并在必要时进行访问。

我可以将整个单个文件作为块读取并使用缓冲区进行操作吗?或者,当文件仅使用seekg读取时,我可以将值推送到堆栈中吗?哪个会更好更容易实施?使用regex的可能性有哪些?

根据输入的格式和大小,我建议按照以下几行来读取和解析输入:

void ParseOneFile (std::istream & inp)
{
    std::vector<std::vector<std::string>> data;
    int some_int_1 = 0, some_int_2 = 0;
    std::string temp;
    data.push_back ({});
    while (0 == 0)
    {
        int c = inp.get();
        if ('$' == c)
        {
            data.back().emplace_back (std::move(temp));
            break;
        }
        else if ('|' == c)
        {
            data.back().emplace_back (std::move(temp));
            data.push_back ({});
        }
        else if ('_' == c)
            data.back().emplace_back (std::move(temp));
        else
            temp += char(c);
    }
    char sharp;
    inp >> some_int_1 >> sharp >> some_int_2;
    assert ('#' == sharp);
    // Here, you have your data and your two integers...
}

上面的函数不会返回它提取的信息,所以您需要更改它。但它确实将您的一个文件读取为一个由称为data的字符串和两个整数(A|B|C|D....|Z$(some integer value)#(some integer value)0和some_int_2)组成的向量向量。它使用C++11,在处理和内存方面都能非常有效地进行读取和解析。

而且,上面的代码不会检查输入文件中是否存在任何错误和不一致的格式。

现在,针对您的数据结构问题。由于我不知道你的数据的性质,我不能肯定。我所能说的是,一个二维数组和两边的两个整数感觉很自然地适合这些数据。由于您有几个文件,您可以将它们全部存储在向量的另一个维度中(或者可能存储在map中,将文件名映射到如下数据结构:

struct OneFile
{
    vector<vector<string>> data;
    int i1, i2;
};
vector<OneFile> all_files;
// or...
// map<string, OneFile> all_files;

上面的函数将填充上面OneFile结构的一个实例。

例如,all_files[0].data[0][0]将是引用第一个文件中的数据项A0的字符串,而all_files[7].data[25][3]将是引用第八个文件中数据项Z3