插入[n X n]矩阵类型的数据,并在运行时对其进行访问.将std::映射工作
Insert an [n X n] matrix type data and access it at run time. Will std::map work?
我有一个[n X n]数据矩阵。第一列是"id",它像主键一样递增(向下)。并且它将从应用程序中读取(或有时写入)。读取通常发生在访问每一行的id时。我想到了以下几点:
- 由于id将是关键,与之相对的是值,因此映射就足够了
- 在获得特定id(键)的值后,可以将数据推送至向量
- 可以基于每个元素的索引来访问该向量
我的疑问是,当n的大小在10000左右时,我的想法会有帮助吗?有其他有效处理矩阵类型数据的方法吗?b树能满足我的要求吗?
您的设计理念非常好。类似数据库的结构可以很容易地存储在地图中。10000个值也不会有任何问题。
要使用的地图类型取决于要存储的数据。对于具有唯一键的表,最快的解决方案是std::unordered_map
。如果要对主键进行排序,则可以使用std::map
。这会稍微慢一点,因为它需要对键进行排序。
对于这两个地图,如果您的密钥不是唯一的,也可以使用多映射解决方案。
阅读和写作也将非常简单。
让我们看一个例子,其中我们使用一个唯一的未排序键(最快的解决方案)。
请参阅:
#include<iostream>
#include<sstream>
#include<vector>
#include<unordered_map>
#include<string>
#include<iterator>
std::stringstream fileStreamSimulation{R"(1 100 101 102 103
2 200 201 202 203 204 205 206 207
3 300 301 302
4 400 401 402 403 404 405
)"};
int main() {
// Define our data container, like a database table with primary index
std::unordered_map<int,std::vector<int>> data{};
// Read all lines from the source file
for (std::string line{}; std::getline(fileStreamSimulation, line); ) {
// Put line into an istringstream for further extraction
std::istringstream iss{line};
// Get the key or primiary index
int key{}; iss >> key;
// Add the rest of the data
data[key] = {std::istream_iterator<int>(iss),{}};
}
// Show debug output
for (const auto [key,vector] : data) {
std::cout << "Key: " << key << "tData: ";
for (const int i : vector) std::cout << i << ' ';
std::cout << 'n';
}
}
相关文章:
- 我想访问std::unique_ptr中的一个特定元素
- 通过unique_ptr访问std::数组
- 访问 std:vector 的类成员 std:vector 在一个类中与另一个 std:vector
- 使用 at() 访问 std::map 元素是否比运算符 [] 慢?
- 通过作为指向 C++ 函数的指针传递来访问 std::array 元素的正确方法是什么?
- 阻止直接访问 std::map 键
- 使用 std::get 访问 std::variant<index>
- 通过引用传递时访问std::vector的元素
- 如何访问std::shared_ptr方法
- SFML访问std::vector内的数组
- 无法访问 std::p air 的成员秒
- 访问"std::vector"的保留但未调整大小的内存作为原始内存是否安全?
- 如何访问"std::variant"的任何子级的"多态"基类?
- 访问 std::multimap 值的最佳方式?
- 如何在C++中从模板化类访问 std::vector 数据
- 在VS2015中访问std::any
- 在 c++ 中访问 std::map 的多个线程
- 在 Valgrind 输出中仍然可以访问 std 线程向量的块
- 用指针访问std ::字符串中的元素
- 在 C++ 中访问 std::array<std::array> 元素