在C++应用程序的使用中,需要对数组、向量和映射进行澄清
Clarification required regarding Arrays, Vectors and Maps in usage of a C++ Application
我想知道适用于我的应用程序的正确算法和容器类。我正在尝试构建一个客户端-服务器通信系统,其中服务器包含一组文件(.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
- 如何在向量数组中插入元素?
- 不同大小的向量数组的大小 cpp
- 很好的语法来获取对向量/数组数据的大小引用?
- 指向 c++ 中的向量数组并将其发送到函数的指针
- 初始化向量数组,其中每个向量的大小为 0
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 如何使用结构体的向量数组?
- C++:向量数组
- 在C++中通过引用传递向量数组
- 向量数组"Cannot access memory at address"
- 构造不同类型的C++向量数组
- 向量数组的均值和众数 - 如何对函数进行较小的改进
- C++:初始化(新)一个不同初始大小的向量数组
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 销毁C++中的向量数组
- 继承向量/数组/列表并更改其大小
- 如何输出属于向量数组的结构字符串
- 如何通过引用传递向量数组
- 在向量数组中获得前五个最大的结果
- 为什么"new vector<int>[5]"不创建向量数组?