向量push_back与对

时间:2019-03-05 16:08:37

标签: c++ vector

我正在geeksforgeeks.org上查看Prim的Algorithim的实现,并尝试在练习模式下实现该功能。我看了如何收到输入,然后看到了:

#include<bits/stdc++.h>
using namespace std;

const int MAX = 1e4 + 5;

int spanningTree(vector <pair<int,int> > g[], int n);

int main()
{
    int t ;
    cin>>t;
    while(t--)
    {
        vector <pair<int,int> > adj[MAX];
        int n,e;
        int w, mC;
        cin >> n>> e;
        for(int i = 0;i < e;++i)
        {
            int x,y;
            cin >> x >> y >> w;
            adj[x].push_back({w, y});
            adj[y].push_back({w, x});
        }

        mC= spanningTree(adj, MAX);
        cout << mC << endl;
    }
    return 0;
}

我在理解他们如何使用vector时遇到了很多麻烦。我从未见过以类似于数组vector <pair<int,int> > g[]的方式传递矢量。

我查看了vector的STD实现,找不到关于以这种方式传递向量或使用vector <pair<int,int> > adj[MAX];构造向量的任何信息。

最后,我对以下代码的功能感到非常困惑:

adj[x].push_back({w, y});
adj[y].push_back({w, x});

我尝试自己实施:

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

using namespace std;

int main()
{
    vector< pair<string, int> > vec[2];
    vec[0].push_back({"One", 1});

    vec[1].push_back({"Two", 2});

    for(int x = 0; x < 2; ++x){
        cout << vec[x].first << ", " << vec[x].second << endl;
    }

    return 0;
}

但是我收到错误消息class 'std::vector< pair<string, int> >' has no member named ‘first’

如果我对了解如何使用vector有所帮助,我将不胜感激。我已经看过多个StackOverflow帖子,包括vector::push_back vs vector::operator[]

原始问题的链接为here

2 个答案:

答案 0 :(得分:6)

I've never seen the passing of a vector in a similar way to an array: vector <pair<int,int> > g[]

It is an array! An array of vectors.

The problem with your code is that you have two vectors, both with a single element, and your loop only pulls out the vectors... not their single element.

Your version would be:

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

using namespace std;

int main()
{
    vector< pair<string, int> > vec[2];
    vec[0].push_back({"One", 1});

    vec[1].push_back({"Two", 2});

    for(int x = 0; x < 2; ++x){
        cout << vec[x][0].first << ", " << vec[x][0].second << endl;
    }

    return 0;
}

All I added was [0] (index into each vector).

Of course such an example is of questionable practicality. In such a situation it would seem that you want one vector with two elements, and no arrays in sight.

To be honest, I'm not wild about the original code, either. Mixing arrays and vectors is a recipe for confusion (hyello); they could have used "2D vectors" or, better, a 1D vector with 2D indexes laid on top of it. That would then have much better cache locality as well.

答案 1 :(得分:3)

它是向量的C样式数组,在这里真的没什么魔术。

int spanningTree(vector <pair<int,int> > g[], int n);

也许您以前看过类似的东西:

int foo( int array[], int n);

在他们的代码中,数组的元素不是int,而是std::vector。为什么它们混合纯数组,而std::vector我不能告诉你。

在您的示例中,您需要先使用operator[]访问元素,然后才能访问其.first.second,或使用front获取第一个元素:

for(int x = 0; x < 2; ++x){
    cout << vec[x].front().first << ", " << vec[x].front().second << endl;
}