c++ - 使用迭代器访问结构元素

标签 c++ pointers vector iterator operators

我已经定义了这个结构体和 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/

相关文章:

c++ - 使用模板与函数的好处以及如何推断模板中的类型

c++ - 在用户定义类型的容器上使用 std::find c++

c++ - CORBA omniorb C++ 多仆人

c# - 在 C# 中使用指针偏移

c++ - 跟踪线程创建点以进行调试

c - c中指针如何在内存中存储字符串

C++:无法从 foo& 转换为 foo*

c++ - 如何将一维数组更改为二维 vector ?

c++ - 对于类中动态大小的数组,std::vector 是否优于堆数组?

c++ - 如何初始化 std::map 项的 std::vector?