简体   繁体   English

C++中基于范围的for循环歧义

[英]Range-based for loop ambiguity in C++

These two pieces of code:这两段代码:

A)一种)

void KMeans<N>::assign_pixels_to_clusters()
{
    for (auto cluster : clusters)
    {
        cluster.clear_pixels();
    }

    for (auto pixel : pixels)
    {
        float min_distance = FLT_MAX;
        Cluster<N> c;

        for (auto cluster : clusters)
        {
            float distance = norm(
                pixel.get_value(),
                cluster.get_centroid()
            );

            if (distance < min_distance)
            {
                min_distance = distance;
                c = cluster;
            }
        }

        c.add_pixel(pixel);
    }
}

and B)和乙)

template <size_t N>
void KMeans<N>::assign_pixels_to_clusters()
{
    for (auto cluster : clusters)
    {
        cluster.clear_pixels();
    }

    for (auto pixel : pixels)
    {
        float min_distance = FLT_MAX;
        int idx = 0;

        for (int i = 0; i < no_of_clusters; i++)
        {
            float distance = norm(
                pixel.get_value(),
                clusters[i].get_centroid()
            );

            if (distance < min_distance)
            {
                min_distance = distance;
                idx = i;
            }
        }

        clusters[idx].add_pixel(pixel);
    }
}

seem similar to me, yet only B) works the way I want to.看起来与我相似,但只有 B) 按照我想要的方式工作。 In the case of A), the pixels are not assigned to clusters at all.在 A) 的情况下,像素根本没有分配给簇。 After the piece of code A) is run, the clusters are empty and have no pixels assigned to them.代码 A) 运行后,簇为空并且没有分配给它们的像素。 Can you help me understand why, please?你能帮我理解为什么吗?

In your A version, you are making a copy of the cluster on this line:在您的A版本中,您正在这一行制作集群的副本:

c = cluster;

So when you do所以当你这样做

c.add_pixel(pixel);

you are not changing the clusters range.您没有更改clusters范围。

For the same reason, this loop:出于同样的原因,这个循环:

for (auto cluster : clusters)
    {
        cluster.clear_pixels();
    }

doesn't actually clear pixels of any cluster in clusters , since each cluster is a copy.实际上并没有清除clusters中任何簇的像素,因为每个cluster都是一个副本。 If you actually want to refer to each cluster in clusters , you need to do this:如果你真的想引用clusters 中的每个clusters ,你需要这样做:

for (auto & cluster : clusters)
    {
        cluster.clear_pixels();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM