+ 2

assign a value in vectors.(C++)

I don't know how assign a value in vectors. For example: std::vector <int> arr; arr[0] = 43; Here compiler stops :/ How to assign a value in index 0 or 1 ... I know it's easy but I can't do it ಠ﹏ಠ Help please ಠ◡ಠ

19th Nov 2020, 1:13 PM
Mani_K_A
3 ответов
+ 5
You need to give "arr" an initial size, otherwise it will be empty and accessing its first element will be undefined behaviour, since you are operating outside the bounds of the vector. Keep in mind that operator [] never inserts an element into the vector, it can only access existing elements. So for example, you could construct the vector with an initial size of 5: std::vector< int > arr( 5 ); And then you could access arr[ 0 ] without problems.
19th Nov 2020, 2:05 PM
Shadow
Shadow - avatar
+ 1
Set an initial size to your vector similar to how static arrays are initialized. std::vector<int> vec(100); std::vector<int> vec(100, 0); // init value 0 of 100 size std::vector<int> vec = {4, 13, 12}; // Init size 3 You could also use functions such as vector.capacity() vector.resize() vector.size() To check how many you have capacity for and increase it as you need.
19th Nov 2020, 2:23 PM
Akib
Akib - avatar