【问题标题】:How do I search index of matrix in file?如何在文件中搜索矩阵的索引?
【发布时间】:2021-11-21 00:53:28
【问题描述】:

假设,我有一个包含 3 列的文件。前 2 列是矩阵的索引,第 3 列是矩阵中该位置的值。

0 0 1
0 1 0
0 2 2
1 0 0
1 1 0
1 2 3
2 0 0
2 1 0
2 2 4

现在我想每次都通过这个循环在这个文件中搜索

for(int a=0; a<8;a=a+2){
for(int b=0; b<8;b=b+2){
for(int c=a; c<2;c++){
for(int d=a; d<2;d++){
//check here c and d is exist in file. if exist then return the 3 column value of that index position and if not then return 0 
}
}
}
}

我不能每次都搜索整个文件中的值,因为它在过去读取文件之前的位置。请帮助我解决我学术界的一个大问题。

【问题讨论】:

  • 你能解释一下矩阵的索引应该是什么吗?从来没有听说过这个......或者解释你想要的输出是什么
  • 不清楚你想做什么。您是否尝试读取文件? “搜索矩阵索引”是什么意思?
  • 对于 9 x 3 矩阵,这似乎是许多嵌套循环的方式。更不用说您的几个循环最多只能达到 8 个,因此会丢失一行。
  • 我想每次通过一个 throw 一个函数来传递 c 和 d 值,并检查这个 c 和 d 值是否在文件中,如果它存在于文件中,然后返回第三列的值跨度>
  • 如果我理解正确,该文件包含矩阵的稀疏表示,每行都是x y value。如果您想“在文件中查找索引”,您应该将所有文件读入std::unordered_map&lt; std::pair&lt;int,int&gt;,int&gt; 之类的内容,然后在该地图中搜索坐标。无论如何,您首先需要阅读该文件。你知道怎么做吗?

标签: c++ algorithm file matrix tensor


【解决方案1】:

使用 std::map 解决您的问题的可能解决方案: 首先我们将每个值以索引作为键,将值作为映射值写入映射中,然后我们可以搜索任何索引:

#include <iostream>
#include <map>
#include <sstream>
#include <string>

int main()
{
    std::stringstream stream(
"\
0 0 1\n\
0 1 0\n\
0 2 2\n\
1 0 0\n\
1 1 0\n\
1 2 3\n\
2 0 0\n\
2 1 0\n\
2 2 4\n\
");

    std::map<std::pair<int,int>,int> map;
    int x, y, value;
    while(stream >> x >> y >> value)
    {
        map.insert({{x, y}, value});
    }

    int c = 0, d = 2;
    auto pos = map.find({c, d});
    if(pos != map.end())
    {
        std::cout << "Value of searched index: " << pos->second << std::endl;
    }

    return 0;
}

【讨论】:

  • 没有make_pair也可以工作:godbolt.org/z/Mvacao1Ka
  • @463035818_is_not_a_number 相应地更新了答案,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
  • 2012-11-06
  • 2012-05-28
  • 2016-08-26
相关资源
最近更新 更多