0

Suppose I've a vector as vector<int>a[n] and while compiling I give value of n as 2 . Can I keep on adding value to this array ?

#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n; int q; cin >> n >> q; vector<int> a[n]; for(int i = 0; i < n; i++){ int m; cin >> m; int o; for(int j = 0; j < m; j++){ cin >> o; a[i].push_back(o); } } int r, s; for(int k = 1; k <= q; k++){ cin >> r >> s; cout << a[r][s] << endl; } return 0; } Like in this code if i give n as 2 can I keep on adding values to the array if yes why?

1st Feb 2022, 1:32 PM
Dreamer
4 odpowiedzi
+ 2
Dreamer before you can add elements beyond the initial size you have to resize the vector. Here is more information: https://www.geeksforgeeks.org/vector-resize-c-stl/
1st Feb 2022, 2:23 PM
Brian
Brian - avatar
+ 1
Dreamer, I didn't clearly get the question. It might help if you can illustrate your intention, with an example ...
1st Feb 2022, 1:40 PM
Ipang
+ 1
Okay let's see, first we make an array of <n> std::vector<int> we name it <a>. Assuming <n> was 2 ... a { std::vector<int> std::vector<int> } Then we forge an inner loop where we read <m>, a number of elementa to be added to the std::vector element, identified by index <i> (defined in outer loop). So here we are inserting <m> elements to the std::vector inside the array. Is it clear now, it's fine if you have questions. I'll try to assist you as I can ...
1st Feb 2022, 2:22 PM
Ipang
0
Okay so when I compile this code I give input of value of n as 2 but as you can see in the first for loop it's repeating m times , let's the suppose the value of m as 4 then the for loop executes 4 times and adds values to the array 'a' ...assuming the elements to 5,6,7,8. But the array as defined in beginning was supposed to have 2 elements how is able to store 4 elements (5,6,7,8). I hope I cleared this question actually I'm not familiar with vectors.
1st Feb 2022, 1:46 PM
Dreamer