c++ 尝试查找 vector<struct>.begin()/.end() 时出错

问题描述

所以在我的项目中有这个东西困扰着我,它阻止我在将 struct 作为向量类型时找到 vector.begin() 和 vector.end()。有人可以帮我吗?

struct product
{
    string name = "";
    int qty = 0,code = 0,cat = 0;
    double price = 0.00;
}

(...)
vector <product> prod;
(...)
for(int i = 0; i != prod.end(); i++) //error here

感谢任何帮助

解决方法

在这个 for 循环中

for(int i = 0; i != prod.end(); i++) 

比较了一个 int 类型的对象和一个 std::vector<product>::iteratorstd::vector<product>::const_iterator 类型的对象

没有为这些类型的操作数定义运算符 !=。

你的意思好像是

for ( auto it = prod.begin(); it != prod.end(); ++it) 

for ( auto it = std::begin( prod ); it != std::end( prod ); ++it) 

并且要访问向量的元素,您应该将表达式 *itit 与运算符 -> 一起使用,就好像 it 是一个指针一样。例如 ( *it ).qtyit->qty

for ( std::vector<product>::size_type i = 0; i != prod.size(); i++ )

在这种情况下,您可以使用下标运算符,例如 prod[i].qty

注意循环对空向量没有意义。

另一种方法是使用基于范围的 for 循环,例如

for ( const auto &p : prod )

for ( auto &p : prod )