从向量C ++返回struct元素

时间:2018-08-05 04:21:55

标签: c++ c++11 struct stl return-value

我是C ++的新手,我正尝试使用2个搜索条件从结构向量中返回一个结构。

函数find_city会向我返回定义范围内的所有内容,无论它是否存在于struct向量中。

这是我的代码:

struct cityLoc
{
    int hRange;
    int vRange;
    int cityCode;
    string cityName;
};

vector<cityLoc> cl1;

// the vector has already been preloaded with data

// function to return my struct from the vector
cityLoc find_city(int hRange, int vRange)
{
    for (size_t i = 0; i < cl1.size(); i++)
    {
        if ((cl1[i].hRange = hRange) && (cl1[i].vRange = vRange))
        {
            return cl1[i];
        }
    }
}

int main()
{
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j <= 8; j++)
        {
            cityLoc this_city;
            this_city = find_city(i, j);
            cout << this_city.hRange << ", " << this_city.vRange << endl;
        }
    }
    return 0;
}

此外,除了这个问题,我以前一直在研究std::find_if,但并不理解。如果我有以下代码,输出是什么?如何修改它以使其返回结构?

auto it = find_if(cl1.begin(), cl1.end(), [](cityLoc& cl) { return cl.hRange == 1; } );

2 个答案:

答案 0 :(得分:2)

您在这里有一个错误:

    if ((cl1[i].hRange = hRange) && (cl1[i].vRange = vRange))

这些=是分配,而不是比较!请启用编译器警告,以后您不会受到此类明显的错字的伤害。

答案 1 :(得分:2)

如果成功,

std::find_if会将迭代器返回找到的结构项,否则返回std::vector::end()。因此,您应该首先验证返回的迭代器是否有效。

例如:

auto it = std::find_if( cl1.begin(), cl1.end(),
                        [](const cityLoc& cl) { return cl.hRange == 1; } );

if ( it == cl1.end() )
{
    // ERROR: Not found! Return error code etc.
    return -1;
}

// And, if found, process it here...

std::cout << it->hRange << '\n';
std::cout << it->vRange << '\n';

std::find_if中的条件(谓词)部分是lambda expression