开发者

Query about Properties Vectors in C++

I am kind of开发者_高级运维 a beginner and just came across the concept of vectors in C++. I have a few questions about it

1. Is there a concept of 2-D vectors in C++? if yes, then how do i declare corresponding to a 2-D Matrix a[n][m]? Here, n and m are variables.

2. How are vectors passed as arguments to functions? By default are they passed by reference or by value?

3. Are there any performance benifits of vectors over arrays in C++?


1 - There's no real concept of dimensions per se. But you can create "nested" types. For example:

std::vector <int> intVec;
std::vector < std::vector <int> > doubleIntVec;

Here, intVec can be compared to single-dimension vector, doubleIntVec to double dimension, and so on. The types don't have to be the same, you can do std::vector < std::vector <char> > doubleIntVec for example, which is why "dimension" is not the right term here.

2 - Like any other type, there's no specific treatment of vectors.

3 - Yes, for example if you need resizing them, but you can implement arrays to behave similarly. Other than that the benefit is the standardization, the memory management that comes built in, the additional methods, and the various STL algorithms that can be run on vectors (being it a standard container).


There's no 2-D vectors in C++, to create a matrix, you can use vectors of vectors.

using namespace std;
int m, n;
// ...
vector<vector<int> > v(n);
for (int y = 0; y < n; y++)
    v[n].resize(m);
// ...

Computing libraries won't implement them this way, though.

To pass a vector by reference to a function, use: void function(vector & v); Omitting the & will result in the vector being copied during the function call.

Vectors have the same performance as C arrays, but are much more practical to use. No need to manually manage the memory, and the vector size is always accessible. You also have automatic copy and guarantees on contiguity of values (raw data can be accessed by vector::data()


vector in C++ is just a sequence container. So, it's possible using it to hold a 2D array.

  1. Using std::vector <std::vector<int>>
  2. It depends on the purpose.
  3. Not perfomance wise, but unlike array, std::vector is growable.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜