Ullan Ullan - 3 months ago 9
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>
#include<set>
#include<map>
#include<iostream>

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;

myset.insert(_struct);
mymap.insert(_struct.name, myset);

return 0;
}


Error:


Error 1 error C2664:
'std::_Tree_const_iterator>>
std::set,std::allocator<_Kty>>::insert(std::_Tree_const_iterator>>,const
person_struct &)' : cannot convert argument 1 from 'person_struct *'
to 'person_struct &&'


Thanks in advance for your help

Answer

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).

Comments