I would like to know how to insert data into a set dynamically.
I have a text file with different points and i need to insert into the set dynamically as i will not know how many items will be there.
sample.txt
Point [3 4]
Point [5 6]
main.cpp
set<Point> s_p2;
if (strData.find("Point") != string::npos) {
pos = strData.find("t");
strData = strData.substr(pos + 2, 4);
istringstream in(strData);
Point temp_p;
in >> temp_p;
s_p2.insert(temp_p);
}
s_p2 is the set container and the following set of codes are looped till the end of the file.
Q1: If I do this, will my set have only 1 item or multiple items of temp_p?
Q2: How can i print out the values in side the set?
.
ostream& operator<<(ostream &out, Point &p2) {
p2.setDistFrOrigin();
out << "[" << setw(4) << p2.getX() << setw(1) << "," << setw(4) << p2.getY() << "] " << setprecision(3) << p2.getScalarValue() << endl;
}
That depends. The set will only store unique
Points, so if thetemp_pare different each time, they will all get stored. The “uniqueness” of aPointis determined using the comparison function used for the set’s ordering.Two elements
AandBare equal ifAis not greater thanBandBis not greater thanA.You should define an
std::ostream& operator<<(std::ostream& os, const Point& p)operator, and then usestd::cout. For example:Then,
or, in c++11