插入[n X n]矩阵类型的数据,并在运行时对其进行访问.将std::映射工作

Insert an [n X n] matrix type data and access it at run time. Will std::map work?

本文关键字:访问 std 工作 映射 运行时 类型 插入 数据      更新时间:2023-10-16

我有一个[n X n]数据矩阵。第一列是"id",它像主键一样递增(向下)。并且它将从应用程序中读取(或有时写入)。读取通常发生在访问每一行的id时。我想到了以下几点:

  1. 由于id将是关键,与之相对的是值,因此映射就足够了
  2. 在获得特定id(键)的值后,可以将数据推送至向量
  3. 可以基于每个元素的索引来访问该向量

我的疑问是,当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';
    }
}