C++ 迭代循环
我写了这段代码:C++ 迭代循环,c++,stl,vector,std,C++,Stl,Vector,Std,我写了这段代码: #define VECTOR_LOOP_V(X) for (vector<typeof(X)>::iterator it = X.begin(); it != X.end(); it++) #为(向量::迭代器it=X.begin();it!=X.end();it++)定义向量循环 为了加快为向量编写for循环的速度,但由于某些原因,它不起作用,当我尝试编译它时,它会给我非常非常长的错误消息 test.cpp: In function ‘int main(in
#define VECTOR_LOOP_V(X) for (vector<typeof(X)>::iterator it = X.begin(); it != X.end(); it++)
#为(向量::迭代器it=X.begin();it!=X.end();it++)定义向量循环
为了加快为向量编写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
test.cpp:在函数“int main(int,char**)”中:
test.cpp:20:5:错误:从“std::vector::iterator{aka _ugnu\u cxx::_normal\u iterator}”转换为非标量类型“std::v”
等等
问题在于几乎所有宏都会多次计算参数,在您的情况下,
它将是一个迭代器,变成一个std::vector
,终止条件会尝试将它与来自不同std::vector的迭代器进行比较,因为typeof(X)它不起作用
生成std::vector
类型,因此宏将扩展为如下内容:
for (vector<std::vector<...> >::iterator it = X.begin(); it != X.end(); it++)
。。下面是一些用法示例:
#include <vector>
#include <iostream>
#define VECTOR_LOOP_V(X) \
for (typeof(X.begin()) it = X.begin(), eit = X.end(); it != eit; ++it)
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
VECTOR_LOOP_V(v) {
std::cout << *it << std::endl;
}
}
#包括
#包括
#定义向量_循环_V(X)\
对于(typeof(X.begin())it=X.begin(),eit=X.end();it!=eit;++it)
int main()
{
std::向量v;
v、 推回(1);
v、 推回(2);
v、 推回(3);
v、 推回(4);
v、 推回(5);
向量_环_V(V){
STD::相信我,C++,这是一个非常短的错误消息。你应该写完整的错误信息,而不是随便删掉某个地方。我打赌第一个字符删掉的时候说的是“代码> STD::vector < STD::vector:ST::Basic字符串……/CODE >。这应该给你一个提示,关于复制结构的左手边。我猜…C++11对你不可用吗?基于范围的for
循环是新的热门。如果你还没有基于范围的for
循环,试试Boost FOREACH。它对C++11中的decltype
有效,但还没有得到正确的支持:@flex,这个答案已经有一年多了,G++4.7处理得很好。@JonathanWakely-really?前几天我在4.7上尝试了一个(类似的)场景,但我无法使它工作。也许你只是忘记了-std=c++11
?谢谢!我将研究基于范围的循环,你的信息真的很有用!
for (vector<std::vector<...> >::iterator it = X.begin(); it != X.end(); it++)
#define VECTOR_LOOP_V(X) \
for (typeof(X.begin()) it = X.begin(), eit = X.end(); it != eit; ++it)
#include <vector>
#include <iostream>
#define VECTOR_LOOP_V(X) \
for (typeof(X.begin()) it = X.begin(), eit = X.end(); it != eit; ++it)
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
VECTOR_LOOP_V(v) {
std::cout << *it << std::endl;
}
}