Square brackets in vectors

I have silly doubts about the vector. In this following code

std::vector<char>ve(2); //creates a vector ve of size 2 std::vector<char>vechar[2]; //but what does it do ? 

in ve vector I can write

 ve[0]='a'; ve[1]='b'; 

but i can't write

 vechar[0]='a'; vechar[1]='b'; 

also i cant do

std::cout << " vector -->>" << vechar[0];

An error is displayed here.

+6
source share
3 answers

std::vector<char>vechar[2] declares an array of two char vectors (this is the same syntax used, for example, int arr[2] ).

Thus, vechar[0] is one char vector, and vechar[1] is another char vector.

Both vectors start empty, but can be changed.

+7
source

Adding more to the NPE answer. To add the character 'a' to vechar [0] or vechar [1], we must do the following:

 vechar[0].resize(10); vechar[1].resize(10); vechar[0][0]='a'; //means vechar 0 0th element vechar[0][1] = 'b'; //means vechar 0 1th element vechar[1][0]='c'; vechar[1][1]='d'; std::cout<<vechar[0][0]<<vechar[0][1]; std::cout<<vechar[1][0]<<vechar[1][1]; 
+1
source

std::vector<char> v[10];

In the above description, an array of 10 empty vectors is created, the same as int v [10];

0
source

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


All Articles