Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square Brackets in Vectors

Tags:

c++

vector

I am having a silly doubt in 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 cannot write

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

also I cannot do

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

It shows error.

like image 505
Freedom911 Avatar asked Sep 27 '14 10:09

Freedom911


People also ask

Do vectors use square brackets?

Vector elements are indexed using the square bracket notation with a starting index of 0 just like arrays.

What do the brackets mean in vectors?

Coordinates and vectors In the Cartesian coordinate system, brackets are used to specify the coordinates of a point. For example, (2,3) denotes the point with x-coordinate 2 and y-coordinate 3. The inner product of two vectors is commonly written as. , but the notation (a, b) is also used.

What is [] used for?

Square brackets, often just called brackets in American English, are a set of punctuation marks that are most often used to alter or add information to quoted material.

What does [] mean in math?

A square bracket at one end of an interval indicates that the interval is closed at that end (i.e., the number adjacent to the opening or closing square bracket is included in the interval).


3 Answers

The std::vector<char>vechar[2] declares an array consisting of two vectors of char (it's the same syntax as used in, for example, int arr[2]).

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

Both vectors start off empty, but can be resized.

like image 129
NPE Avatar answered Oct 29 '22 22:10

NPE


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

The above declaration creates an array of 10 empty vectors, same as int v[10];

like image 29
akhil nichenametla Avatar answered Oct 29 '22 22:10

akhil nichenametla


Adding more to the answer of NPE .To add character 'a' to vechar[0] or vechar[1] we have to do the following things

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];
like image 44
Freedom911 Avatar answered Oct 29 '22 22:10

Freedom911