C++ Map of integers as key and class objects vector as value

Is it possible to add a vector of class objects in a map as value? If so, how can I insert an int as key and a vector of classes as value into a map and how to display the objects in the vector?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  class Account {
    private:
    std::string name;
    double num1;
    int num2;

    public:
    Account() = default;
    Account(std::string name, double num1, int num2) : name { name }, num1 { num1 }, num2 { num2 } {}
    std::string getName() { return name; }
    double getNum1() { return num1; }
    int getNum2() { return num2; }
    ~Account() = default;
};
int main{
    std::map<int, std::vector<Account>> mp;

return 0;
}
L15: needs ()

Is it possible to add a vector of class objects in a map as value?

Yes.

If so, how can I insert an int as key and a vector of classes as value into a map and how to display the objects in the vector?

The same way you would insert anything else in a std::map.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <string>
#include <vector>
#include <utility>
#include <map>

class Account {
private:
    std::string name;
    double num1;
    int num2;

public:
    Account() = default;
    Account(std::string name, double num1, int num2) : name{ name }, num1{ num1 }, num2{ num2 } {}
    std::string getName() { return name; }
    double getNum1() { return num1; }
    int getNum2() { return num2; }
    ~Account() = default;
};

typedef std::vector<Account> acct_vec_t;

int main ()
{
    std::map<int, acct_vec_t> mp;
    int some_int{ 42 }; 
    acct_vec_t some_vec;

    mp.insert(std::pair<int, acct_vec_t> (some_int, some_vec));
    return 0;
}


Last edited on
Thank you!
I figured out how to display the objects, I'll leave the code here if someone else needs this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <string>
#include <vector>
#include <utility>
#include <map>
class Account {
private:
	std::string name;
	double num1;
	int num2;
	friend std::ostream& operator<<(std::ostream& os, std::vector<Account> mp) {
		for (auto i : mp) {
			os << " " << i.getName() << " " << i.getValue() << " " << i.getNum() << endl;
		}
		return os;
	}
	
public:
	Account() = default;
	Account(std::string name, double num1, int num2) : name{ name }, num1{ num1 }, num2{ num2 } {}
	std::string getName() { return name; }
	double getValue() { return num1; }
	int getNum() { return num2; }
	~Account() = default;
};

typedef std::vector<Account> vec;

int main()
{
	std::map<int, vec> mp;
	int num = 100;
	vec some_vec;
	some_vec.emplace_back("Test", 5.5, 8);
	mp.insert(std::pair<int, vec>(num, some_vec));
	
	for (auto i : mp) {
		cout << i.first << i.second << endl;
	}
Topic archived. No new replies allowed.