通过给定ID从列表中获取对象

时间:2019-11-10 23:50:08

标签: c++ list

为了在C ++中实现埃德蒙的基数匹配算法,我为图的顶点创建了一个新结构,该结构存储了该算法所需的更多信息以及一个函数,该函数通过放入其id来获取顶点。但是,它没有做,应该做。

我希望函数getVertex(ED :: NodeId x,std :: list vertecies)退还ID为x(这是第一个参数v)的列表顶点中的顶点。相关代码如下:

struct vertex 
{
ED::NodeId v;
ED::NodeId m;
ED::NodeId f;
ED::NodeId r;
int scanned;
void setM(vertex neigh);
void setF(vertex neigh);
void setR(vertex neigh);
void setScanned(int scan);
} vrtex;


vertex getVertex(ED::NodeId x, std::list<vertex> vertecies)
{
for (std::list<vertex>::iterator it = vertecies.begin(); it!=vertecies.end(); ++it)
{
    if(it->v == x)
    {
        return (vertex) * it;
    }
}
printf("No element with id %i found.", x);

return createVertex(0); //If there is no suche node id in vertecies

}

如果我插入getVertex(vert.m,vertecies),我总是得到顶点vert,而不是由vert.m索引的顶点,我觉得这与指针有关,我不完全了解它的功能,因为我是C ++的新手。感谢您修复我的功能。

1 个答案:

答案 0 :(得分:0)

我实际上没有得到您的问题所在。我运行您的代码,并按索引正常返回顶点。 这是代码:

#include <iostream>
#include <list>

namespace ED
{
    typedef int NodeId;
}

struct vertex 
{
ED::NodeId v;
ED::NodeId m;
ED::NodeId f;
ED::NodeId r;
int scanned;
void setM(vertex neigh);
void setF(vertex neigh);
void setR(vertex neigh);
void setScanned(int scan);
} vrtex;


vertex getVertex(ED::NodeId x, std::list<vertex> vertecies)
{
    for (std::list<vertex>::iterator it = vertecies.begin(); it!=vertecies.end(); ++it)
    {
        if(it->v == x)
        {
            printf("Element found!\n");
            return (vertex) * it;
        }
    }
    printf("No element with id %i found.", x);

    return vertex(); // If there is no suche node id in vertecies
} 

int main()
{
    std::list<vertex> vertices = 
    {
        {0,0,0,0,0},
        {1,0,0,0,0},
        {2,0,0,0,228},
        {3,0,0,0,0}
    };

    printf("%d\n", vertices.size());

    vertex e = getVertex(2, vertices);
    printf("Element.scanned = %d\n", e.scanned);
    vertex vert = {0,2,0,0,0};
    e = getVertex(vert.m, vertices);
    printf("Element.scanned = %d\n", e.scanned);
}

输出:

[DDRDmakar@localhost New Folder]$ g++ test.cpp && ./a.out
4
Element found!
Element.scanned = 228
Element found!
Element.scanned = 228

也许我使用了错误的类型或参数,但是它起作用了...
但是使用for-each循环会更好。它的工作方式相同,但更安全:

vertex getVertex(ED::NodeId x, std::list<vertex> vertecies)
{
    for (const auto &e : vertecies)
    {
        if(e.v == x)
        {
            printf("Element found!\n");
            return e;
        }
    }
    printf("No element with id %i found.", x);

    return vertex(); // If there is no suche node id in vertecies
}