微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

打印映射的键值对,其中键是 C++ 中的向量

如何解决打印映射的键值对,其中键是 C++ 中的向量

我有一个 2d 向量来表示图形上的点。我试图找到这些点与原点之间的欧几里得距离。

这是我的代码

我的想法是将点映射为向量作为其欧几里得距离作为值的键。我能够做到,但我无法使用键值对打印地图。如何打印地图以查看值

#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <map>
#include <string>
#include <numeric>
#include <set>
#include <unordered_set>

using namespace std;

int main()
{
    vector<vector<int>> points = { {3,3},{5,-1},{-2,4} };

    unordered_map<vector<int>,double> mp;

    //for loop to find euclidean distance of each data point and then insert into map
    for (int i = 0; i < points.size(); i++)
    {
        int sum = 0;
        vector<int> alpha;  //temporary vector to store the data points 
        
        for (int j = 0; j < points[i].size(); j++)
        {
            sum = sum + (points[i][j] * points[i][j]);
            alpha.push_back(points[i][j]);
        }
        double res = sum;
        res = sqrt(res); //finding sqrt for euclidean distance
        mp.insert({ alpha,res });  //inserting into the map
        alpha.clear();
    }
  
    //Trying to print the map but isn't working
    for (auto itr = mp.begin(); itr != mp.end(); ++itr) {
        cout << itr->first
            << '\t' << itr->second << '\n';
    }

    return 0;
}

错误:C2679 二进制“

解决方法

首先,std::vector 键没有哈希函数,因此您需要以其他方式使用 std::unordered_map

std::unordered_map<double,std::vector<int>> mp;

你可以有一个单独的函数来打印出 std::vector 的元素,因为 operator<< 没有为 std::vector 类型重载:

template <typename T>
void print_vec(std::vector<T> const& v) {
    bool is_first{ true };
    std::cout << "{ ";
    for (auto const i : v) {
        if (is_first) {
            is_first = false;
            std::cout << i;
        } else {
            std::cout << "," << i;
        }
    }
    std::cout << " }";
}

然后:

for (auto const& it : mp) {
    cout << it.first << '\t';
    print_vec(it.second);
    cout << '\n';
}
,

您可以为 << 定义一个 vector,或者在打印地图时将其内联写入。

for (auto & [vec,sum] : mp) {
    for (auto & point : vec) {
        std::cout << point << " "
    }
    std::cout << '\t' << sum << '\n';
}

您还需要为 vector 定义一个 Hash 以将其用作地图的键。

template <typename T,typename ElemHash = std::hash<T>>
struct sequence_hash {
    template <typename C>
    std::size_t operator()(const C & container) {
        std::size_t res = size_hash(container.size());
        for (auto & v : container) { 
            /* some combiner */
            boost::hash_combine(res,elem_hash(v)); 
        }
        return res;
    }

private:
    std::hash<std::size_t> size_hash;
    ElemHash elem_hash;
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。