c++ - STL 迭代器循环

标签 c++ stl vector std

我写了这段代码:

#define VECTOR_LOOP_V(X) for (vector<typeof(X)>::iterator it = X.begin(); it != X.end(); it++)

为了更快地为 vector 编写 for 循环,但由于某种原因它不起作用,当我尝试编译它时,它给了我非常非常长的错误消息。

 test.cpp: In function ‘int main(int, char**)’:
test.cpp:20:5: error: conversion from ‘std::vector<std::basic_string<char> >::iterator {aka __gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >}’ to non-scalar type ‘std::v

等..

最佳答案

#define VECTOR_LOOP_V(X) \
     for (vector<typeof(X)>::iterator it = X.begin(); \
          it != X.end(); it++)

您打算如何使用宏?看起来像 X是容器,在这种情况下,for 的第一部分应该类似于 typeof(X)::iterator (甚至不知道这是否合法,因为 typeof 不是标准的并且从未使用过)。

或者,您可以只使用 boost::foreach,它提供了一个类似但更丰富的宏,其优点是在许多方面更安全。例如,如果参数是按值返回的函数调用,您的宏将严重中断:

std::vector<int> f();
VECTOR_LOOP_V( f() ) {
   std::cout << *it << "\n";
}

问题与几乎所有你多次计算参数的宏一样,在你的情况下是it将成为一个迭代器 std::vector<int>终止条件将尝试将它与来自不同 std::vector<int> 的迭代器进行比较.

关于c++ - STL 迭代器循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11586366/

相关文章:

用于求解复杂线性系统 Ax=b 的 C++ 库

c++ - 如何删除回收站中路径太长的文件夹或文件?

c++ - malloc 创建时 std::queue 的默认大小

c++ - GCC 警告将函数指针转换为对象指针

c++ - 将类成员数组组合到单个数组时性能受到影响

c++ - 针对编译时间优化的 STL 版本?

c++ - 用C++实现LRU缓存

c++ - unordered_map<int,int> 如何处理负元素?

c++ - 自制 vector 类的重载 = 运算符

c++ - vector<struct> 的自定义迭代器