vector<pair<int, int>>怎么输出第一个元素
时间: 2023-04-05 09:03:56 浏览: 98
您可以使用循环遍历vector,然后使用pair的first成员来输出第一个元素。例如:
for (auto& p : vec) {
std::cout << p.first << std::endl;
}
其中,vec是您的vector对象。
相关问题
二维vector<vector<pair<int,int>>>
二维 vector<vector<pair<int,int>>> 表示了一个二维数组,其中每个元素是一个 vector,而每个 vector 中的元素是一个 pair,pair 中存储了两个 int 类型的值。
这种数据结构通常用于表示稀疏矩阵,其中第一维表示行,第二维表示列,每个元素是一个非零的值和它的列坐标。例如,下面是一个 3x4 的稀疏矩阵:
```
0 0 0 0
0 0 2 0
0 3 0 0
```
可以用以下代码来表示:
```cpp
vector<vector<pair<int,int>>> mat(3);
mat[1].push_back({2, 2});
mat[2].push_back({3, 1});
```
其中 mat[1][0] 表示第 2 行第 3 列的值为 2,mat[2][0] 表示第 3 行第 2 列的值为 3。其它位置都是 0,可以省略不存储。
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).