C++ vector<pair<int, int>>
时间: 2023-08-10 18:02:47 浏览: 381
C++中的`vector`是一个动态数组,可以存储一组同类型的数据。而`pair`是一种结构体模板,可以将两个不同类型的值组合在一起。
因此,`vector<pair<int, int>>`就是一个存储了一组`pair`结构体的动态数组,其中每个`pair`结构体包含两个`int`类型的值。可以使用以下代码来创建一个`vector<pair<int, int>>`类型的变量:
```cpp
#include <vector>
#include <utility>
std::vector<std::pair<int, int>> myVec;
```
可以使用`push_back`函数向`vector`中添加新元素:
```cpp
myVec.push_back(std::make_pair(1, 2));
```
这将在`myVec`中添加一个新元素,其值为`pair<int, int>(1, 2)`。可以使用下标运算符或迭代器来访问`vector`中的元素:
```cpp
std::cout << myVec[0].first << " " << myVec[0].second << std::endl; // 输出 1 2
```
相关问题
vector<vector<pair<int,int>>>
This is a vector of vectors, where each element of the outer vector is a vector of pairs of integers.
For example,
```c++
vector<vector<pair<int,int>>> v;
```
creates an empty vector of vectors. To add a vector of pairs to this, we can do:
```c++
vector<pair<int,int>> inner; // create an inner vector
inner.push_back(make_pair(1,2)); // add a pair to the inner vector
inner.push_back(make_pair(3,4)); // add another pair to the inner vector
v.push_back(inner); // add the inner vector to the outer vector
```
Now, `v` contains one vector of pairs:
```
v = [
[(1,2), (3,4)]
]
```
We can add more vectors of pairs to `v` in a similar way.
This data structure is useful for storing a collection of pairs where each pair belongs to a different group or category. For example, if we are storing the grades of students in a class, we can have a vector for each subject and each vector contains pairs of (student_id, grade).
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq
This is a declaration of a priority queue in C++ that stores pairs of integers. The priority queue is implemented using a min-heap, which means that the smallest element will have the highest priority. The first integer in the pair is the priority and the second integer is the value.
The syntax for declaring a priority queue in C++ is:
priority_queue<data_type, container_type, comparison_function>
In this case, the data type is a pair of integers (pair<int, int>), the container type is a vector (vector<pair<int, int>>), and the comparison function is the default less-than operator (>).
However, in order to implement a min-heap, we need to use the greater-than operator (<) instead. So we pass greater<pair<int, int>> as the comparison function.
Overall, this priority queue will store pairs of integers in ascending order of their first element. If two pairs have the same first element, then they will be ordered based on their second element in ascending order as well.
阅读全文