3

前几天我解决了另一个涉及std::vector <std::pair<int,int>>被调用的问题name

我的问题是,我如何访问这种类型的name.firstand name.second

我最终使用了 ranged-for 循环,这解决了我的问题

for(i : name) { i->first , i->second}

但是,还有别的办法吗?我对如何在正常for循环中访问它特别感兴趣,例如

for(int i = 0; i < name.size(); i++) { std::vector::std::pair::name.first}

有人可以为我解释一下吗?

4

7 回答 7

5

在 C++17 中,您可以使用结构化绑定

for (auto & [a, b] : name) {
    // a is a reference to the first of each pair
    // b is a reference to the second of each pair
}
于 2021-01-29T15:17:31.780 回答
4

通常的方式

for (size_t i = 0; i < name.size(); i++)
{
     cout << name[i].first;
     cout << name[i].second;
}

这只是访问结构向量(或数组)的典型方式。

顺便说一句,你说的代码实际上没有,for(i : name) { i->first , i->second}应该是for(i : name) { i.first , i.second}. 您的版本适用于对指针的向量,但不适用于对向量。

于 2021-01-29T15:14:05.060 回答
2

如果您使用 C++17(或更高版本)结构绑定可以做到这一点

#include <vector>
#include <utility>

int main()
{
    std::vector <std::pair<int,int>> vp;

    for (auto & [first,second] : vp)
    {
        // do something with first and second
    };
}

请参阅https://en.cppreference.com/w/cpp/language/structured_binding

于 2021-01-29T15:18:24.333 回答
2

从 C++17 开始,您可以使用结构化绑定

#include <iostream>
#include <vector>
#include <tuple>

int main() {
    std::vector<std::pair<int,int>> v{};
    v.push_back({1, 11});
    v.push_back({2, 22});
    for (auto [a, b] : v) {
        std::cout << a << " " << b << "\n";   
    }  // 1 11
       // 2 22
}

请注意,auto在结构化绑定声明中,意味着每一对都是按值获取的(这在使用基本类型时是合理的)。

如果您想读取非基本类型,或通过结构化绑定标识符写入,您可以分别使用auto const&auto&。例如:

// add 'first' to 'second;
for (auto& [a, b] : v) {
    b += a;  
}  // 1 11
   // 2 22

// read only (by value)
for (auto [a, b] : v) {
    std::cout << a << " " << b << "\n";   
}  // 1 12
   // 2 24
于 2021-01-29T15:18:41.373 回答
2

还有结构化绑定

#include <iostream>
#include <vector>
#include <utility>

int main()
{
    std::vector<std::pair<int, int>> somePairs{ {1, 2}, {5, 10}, {12, 60} };

    for (auto [first, second] : somePairs)
    {
        std::cout << "First = " << first << ", second = " << second << '\n';
    }

    return 0;
}

std::pair这会自动将s 内的 s解压缩std::vectorfirstandsecond变量中。

输出:

First = 1, second = 2
First = 5, second = 10
First = 12, second = 60
于 2021-01-29T15:18:43.307 回答
0

这是关于 C++ 语法的一个非常基本的问题。我推荐一本书而不是 Stack Overflow。

优雅的方法是:

std::vector<std::pair<int, int>> names;
for(int i = 0; i < names.size(); i++) {
    auto &name = names[i];
    // now access name.first, name.second
}
于 2021-01-29T15:14:41.993 回答
-1
unordered_map<int , int> mp;
for(auto x:mp)
{

    cout<<x.first;
    cout<<x.second;
}

这是您可以通过创建具有键值对的容器和具有唯一对的映射值来访问标准模板库 (STL) 中的第一和第二成员的方式。

于 2021-01-29T17:35:11.667 回答