Difference between foo [i] and foo-> at (i) with stl-vector

is there a reason why

foo = (bar-> at (x)) β†’ at (y);

works but

foo = bar [x] [y];

doesn't work, where bar is a vector of vectors (using C ++ stl)

announcement:

std :: vector <std :: vector <Object * * * *>

+3
source share
7 answers

Is it a vector of vectors or a vector of pointers to vectors? Your code should work as advertised:

typedef std::vector<int> vec_int;
typedef std::vector<vec_int> multi_int;

multi_int m(10, vec_int(10));

m.at(2).at(2) = /* ... */;
m[2][1] = /* ... */;

But your code is as follows:

typedef std::vector<vec_int*> multi_int; // pointer!
multi_int* m; // more pointer!

If you have pointers, you first need to dereference them to use operator[]:

(*(*m)[2])[2] = /* ... */;

It can be ugly. May temporarily use links:

multi_int& mr = m;
(*mr[2])[2] = /* ... */;

. , :

template <typename T>
typename T::value_type& access_ptr(T* pContainer,
                                    unsigned pInner, unsigned pOuter)
{
    return (*(*pContainer)[pInner])[pOuter]);
}

access_ptr(m, 2, 2) = /* ... */

. , , . , boost .

, . at operator[] , at . .

+9

, ? ,

foo = bar[x][y];

foo = bar.at(x).at(y);

at.

bar->at(x)->at(y) , , , (*(*bar)[x])[y], bar[x][y], , bar .

+4

, bar ( ), :

(*(*foo)[x])[y]
+1

bar , :

(*bar)[x][y]

:

(*(*bar)[x])[y]

.

+1

, ...

, , ,

foo = (* ((* bar) [x])) [Y];

(.. std::vector < std::vector < datatype β†’ .

: , , , , , [].

+1

, "" " ". , " "? , at , operator[] .

, bar not . , . ( . , . new? )

, operator[] , , , - , . (*(bar+x))[y] - , , undefined, foo, .

0

foo = (bar->at(x))->at(y);

To work, there barmust be a pointer, and the vector that it points to must contain pointers.

For

foo = bar[x][y];

barmust be vector(not a pointer) containing vectors (not pointers).

0
source

Source: https://habr.com/ru/post/1728381/


All Articles