user3091585
user3091585

Reputation: 41

How to use a vector of structs in a vector structs in c++?

I want to create a vector of trains, where each train needs a vector of pairs.

If I run the code outside of main(), I get these errors:

naive-bayes.cpp:17:15: error: template argument 1 is invalid
    vector<pair> pairs;

naive-bayes.cpp:17:15: error: template argument 2 is invalid

Inside main(), I get these errors:

naive-bayes.cpp:22:15: error: template argument for 'template<class>
class std::allocator' uses local type 'main()::pair'
    vector<pair> pairs;

naive-bayes.cpp:22:15: error:   trying to instantiate 'template<class> class std::allocator'

naive-bayes.cpp:22:15: error: template argument 2 is invalid

Here is the code:

struct pair {
    int index;
    int value;
};

struct trains {
    string label;
    vector<pair> pairs;
};

Upvotes: 0

Views: 651

Answers (2)

21koizyd
21koizyd

Reputation: 2013

You're problem is probably due to using namespace std;.

There is a std::pair type in the standard library.

Try this:

#include <string>
#include <vector>

struct pair {
    int index;
    int value;
};

struct trains {
    std::string label;
    std::vector<pair> pairs;
};

int main()
{
    return 0;
}

Upvotes: 3

Patrick Kelly
Patrick Kelly

Reputation: 1381

Without a full program example to play with, all I can really point out is that your local pair declaration is likely getting confused with std::pair. Change your definition of struct pair to be struct mypair.

Upvotes: 2

Related Questions