c++中迭代器上的操作

Operation over iterators in c++

本文关键字:操作 迭代器 c++      更新时间:2023-10-16

我有一些问题在翻译一些行代码从ANSI C和数组,到c++与向量。

为了沿着数组元素进行迭代操作,在ANSI C中,我这样写:

int i;
struct Sys{
   double *v;
};
Sys sys; sys.v = malloc(10*sizeof(double));
//initialize the array with some values...
{...}
for (i = 5; i < 10; i++){ //overwrite the cumulative sum starting from position 4
   sys.v[i] =  sys.v[i] + function_that_return_a_double(i);
}

现在,我将在c++中使用向量进行转换。这是我的试验。

Sys {
    vector<double> v;
};
Sys sys;
sys.v.resize(10);
// initialize the vector with some values...
{...}
for (vector<double>::iterator it = sys.v.begin() + 5; it != sys.v.end(); ++it){ //yyy
   k = k+1;
   tmp = function_that_return_a_double(k);
   *it = *it + tmp; //xxx
}

但是我得到以下错误:

code.cpp:xxx: error: name lookup of ‘it’ changed for ISO ‘for’ scoping
code.cpp:xxx: note: (if you use ‘-fpermissive’ G++ will accept your code)

如果我用-fpermissive编译,我得到:

code.cpp:xxx: warning: name lookup of ‘it’ changed for ISO ‘for’ scoping
code.cpp:yyy: warning:   using obsolete binding at ‘it’
我不明白这是否是使用迭代器和STD的正确方法:vector

我希望你能解决我的疑问,

欢呼,

PS:我更正了c++中v的声明。V不是指针!PPS:代码片段很好!!见下文。

您需要将Sys声明为结构体或类:

struct Sys {
    vector<double> *v;
};

您正在尝试访问v,就好像它是向量一样。使用->,因为它是指向向量的指针。

Sys sys;
sys.v->resize(10);
for (vector<double>::iterator it = sys.v->begin(); it != sys.v->end(); ++it) {
    *it += function_that_returns_a_double(k); // Define k somewhere.
}