我是 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/