c++ - Passing a reference to an offset position in an STL vector -


i'm trying convert old c functions c++. original programme stores matrix in single array, , pass pointer first element function working on correct row, e.g.

double f1(int *a){  return a[0] + a[1]; }  int main(void){   int x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};   for(i = 0; < 5; i++){   printf("%d\n", f1(&x[2 * i])); } 

i able similar using stl without copying. programme this

double f1(vector<int>& a){  return a[0] + a[1]; } int main(void){   int x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};   vector<int> y(x, x + 10);    for(i = 0; < 5; i++){      cout << f1(y) << endl; // wrong } 

how this? change function receive reference vector::iterator guess, there way?

you pass iterator function. random access iterators similar pointers (in fact, pointers qualify random access iterators.) example,

#include <vector>  double f1(std::vector<int>::const_iterator a) {     return a[0] + a[1]; }  #include <iostream>  int main() {   vector<int> y{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};    auto = y.cbegin();    for(int = 0; < y.size()/2; ++i)       std::cout << f1(it + 2*i) <<std::endl; } 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -