c++中迭代器上的操作
Operation over iterators in c++
我有一些问题在翻译一些行代码从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.
}
相关文章:
- 迭代器的指针操作问题
- 标准上的 OMP 和并行操作::set<...>::迭代器
- 如何让迭代器使用赋值运算符对列表进行操作
- 将迭代器放置为临时范围时,非销钉 - 操作和错误
- STD ::向量迭代器类型和允许的操作
- 这个迭代器操作在 C++ 中是未定义的吗?
- C++:为什么输出迭代器不支持比较操作?
- 使用迭代器执行对象操作的函数
- std::反向使用反向迭代器,为什么不是无操作?
- C 迭代器操作未检查溢出
- C++列表迭代器如果列表更改则重新启动操作
- std::set::迭代器和std::set::const_iterator之间是否存在操作差异
- 单元测试时操作迭代器
- boost::精神访问从语义操作定位迭代器
- std::sort 如何仅使用迭代器实现交换操作
- 是否允许抛出标准迭代器操作
- C++映射键/迭代器操作
- c++中迭代器上的操作
- 迭代器操作不起作用
- 操作迭代器列表+指针