我已经定义了这个结构体和 vector :
struct All
{
string name;
int id;
};
vector<All*> all;
我正在使用 lower_bound 函数将创建的包含数据的结构插入 vector 以保持排序。
All * tmp = new All(name, id);
auto it = lower_bound(all.begin(), all.end(), name, compare2());
all.insert(it, tmp);
当我想用 name = test
查找结构时我这样做:
auto it1 = lower_bound(all.begin(), all.end(), name, compare2());
它给了我迭代器 it
到名称中包含测试的那个结构,但为什么我不能像这样访问结构的元素 cout << it1 -> id;
?我如何访问该结构的元素?
最佳答案
可以通过以下方式实现
cout << ( *it ) -> id;
表达式 *it
给出 vector 中作为指针的元素。
关于c++ - 使用迭代器访问结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36296499/