I need to dynamically allocate an array of 5 vectors
of pairs
. This code snippet is supposed to add first elements to all 5 vectors
:
std::vector<std::pair<int, int>> * arr = new std::vector<std::pair<int, int>>[5];
for (int i = 0; i < 5; i++) {
arr[i].push_back(std::make_pair(i+1, i+11));
}
But it adds only 1 element to arr[0]
vector
for (auto el : *arr) {
std::cout << el.first << ", " << el.second << std::endl;
}
Printing out gives 1, 11
What I need is
1, 11
2, 12
3, 13
4, 14
5, 15
Please give me some hints. How to work with dynamic vector of pairs?
EDIT: Vector of vectors is one possible way. However, I want to use an array of vectors.
Note : Edited entire answer because of the edit of the question.
The statement:
for (auto el : *arr) {
std::cout << el.first << ", " << el.second << std::endl;
}
will print the element(s) for the first vector only (ie arr[0]
). That's because arr
will decay as a pointer to the first element of the array.
If you want to print for all vector s , you need to iterate over the size of the array (as already done for the insertion):
for (int i = 0; i < 5; i++) {
// arr[i] now is the i-th vector, and you can print whatever you want
// For example the following will print all element for each vector.
for (auto el : arr[i]) {
std::cout << el.first << ", " << el.second << std::endl;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.