c++ - 获取 std::vector 的迭代器的更短方法

标签 c++ vector iterator std stdvector

假设我有一个这样的 vector 。

std::vector<a_complicated_whatever_identifier *> *something
    = new std::vector<a_complicated_whatever_identifier *>;
// by the way, is this the right way to do this?

现在我想为此获得一个迭代器...所以我会这样做。

std::vector<a_complicated_whatever_identifier *>::iterator iter;

但我发现它对我的代码来说有点太多了。我想知道,是否还有更简单的方法来请求迭代器而不考虑类型?

我在想类似的东西。

something::iterator iter;
    // OK, don’t laugh at me, I am still beginning with C++

好吧,它显然失败了,但我猜你明白了。如何完成这个或类似的事情?

最佳答案

您通常会给您的容器合理的 typedef,然后就变得轻而易举了:

typedef std::pair<int, Employee> EmployeeTag;
typedef std::map<Foo, EmployeeTag> SignInRecords;

for (SignInRecords::const_iterator it = clock_ins.begin(); ... )
           ^^^^^^^^^^^^^^^^^

通常,为容器提供一个方便的 typedef 比迭代器的显式 typedef 更实用和 self 记录(想象一下,如果您正在更改容器)。

在新的 C++ (11) 中,您可以说 auto it = clock_ins.cbegin() 来获取常量迭代器。

关于c++ - 获取 std::vector 的迭代器的更短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7505654/

相关文章:

c++ - 如何初始化包含opencv :matrices?的二维 vector

c++ - 将类 vector 的元素设置为等于类时的行为

java - 如何避免在列表迭代中使用 get(0)

c++ - vector 迭代器的增量/减量

c++ - 是否有任何可观察的 Qt 容器类?

c++ - C++类:编写函数的不同方法

c++ - C++中的参数类

c++ - 为什么CUDA不会导致C++代码加速?

python - 将值添加到 PySpark 中的 DenseVector 中

c# - C#中迭代器和数组的区别