c++ - 从 vector C++ 返回结构元素

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

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

find_city 函数返回定义范围内的所有内容,无论它是否存在于结构 vector 中。

这是我的代码:

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; } );

最佳答案

这里有一个错误:

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

那些 = 是赋值,不是比较!请启用编译器警告,这样您以后就不会受到如此明显的拼写错误的伤害。

关于c++ - 从 vector C++ 返回结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51691365/

相关文章:

c++ - 在 C++ 中,如何在列表中每次运行连续零时删除除 x 之外的所有零?

c - 如何在 C 中定义指向结构的全局指针?

使用结构数组调用 C 函数

c++ - 将结构从 C++ dll 返回到 Python

c++ - 在 C++ 中创建 Xml 字符串

c++ - 如何通过 Qt 创建 Web 服务

c++ - 是否定义为 C++ 标准算法提供倒置范围?

c++ - 完美转发可变参数模板到标准线程

c++ - 从 Windows 10 的任务栏中删除窗口

c++ - 学习 Lua 与 C++ 一起使用的资源?