Ullan Ullan - 1 year ago 154
C++ Question

How to insert structure object to set in C++

I am trying to add some items to set and map but insert to the map and set giving an error

#include "stdafx.h"
#include <string>
#include <fstream>

using namespace std;

typedef struct
long number;
std::string name;
double amount;
long volume;
} person_struct;

person_struct _struct;
set<person_struct> myset;
map < string, set<person_struct>> mymap;

int main(int argc, char* argv)
_struct.number = 100;
_struct.name = "TOM";
_struct.amount = 111;
_struct.volume = 230;

mymap.insert(_struct.name, myset);

return 0;


Error 1 error C2664:
person_struct &)' : cannot convert argument 1 from 'person_struct *'
to 'person_struct &&'

Thanks in advance for your help

Answer Source

std::set is an ordered set of unique elements, so you have to define operator < for your struct.

On the other hand, you could use std::unordered_set - then you'd have to specialize std::hash functor for your struct (or provide some other hasher as unordered_set template argument).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download