2012-11-14 77 views
0

我想知道如何动态地将数据插入到集合中。 我有一个不同点的文本文件,我需要动态插入到集合中,因为我不知道有多少项目会在那里。动态插入到集合

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是该组容器和下面的代码集被环直到文件的末尾。 Q1:如果我这样做,我的套装只有1件或多件temp_p?第二季度:我怎样才能打印出侧面的价值?

ostream& operator<<(ostream &out, Point &p2) { 
    p2.setDistFrOrigin(); 
    out << "[" << setw(4) << p2.getX() << setw(1) << "," << setw(4) << p2.getY() << "] " << setprecision(3) << p2.getScalarValue() << endl; 
} 
+1

您的编辑完全改变了问题,因此发布的答案没有意义。我已经回到原来的问题;如果您有更多问题,请分别提问。要回答你的新问题:你需要声明成员函数'const',比如'类型getX()const',以便在声明为'const'的对象上调用它们。 –

回答

4

Q1: If i do this will my set have only 1 item or multiple items of temp_p

那要看情况。该组将只存储唯一Point s,所以如果temp_p每次都不同,它们将全部被存储。 Point的“唯一性”是使用用于该集合排序的比较函数确定的。 如果A不大于BB不大于A,则两个元素AB是相等的。

Q2 How can i print out the values in side the set?

你应该定义一个std::ostream& operator<<(std::ostream& os, const Point& p)操作,然后使用std::cout。例如:

std::ostream& operator<<(std::ostream& os, const Point& p) 
{ 
    return os << p.someMethod() << " " << p.someOtherMethod(); 
} 

然后,

std::set<Point> pointSet = ....; 
for (std::set<Point>::const_iterator it = pointSet.begin(); 
    it!= pointSet.end(); 
    ++it) 
{ 
    std::cout << *it << "\n"; 
} 

,或者在C++ 11

for (const auto& p : pointSet) 
{ 
    std::cout << p << "\n"; 
} 
+0

我已经创建了我的point类中的overloadig操作符。但我怎么能打印出我的设置中的元素 –

+0

@ user1571494我添加了一个示例。 – juanchopanza

+0

我不明白你的......; –

1

假设所有代码的工作:

Q1〜你会得到多个因为每次代码运行时都会创建一个新的temp_p,然后在您将它复制到集合中时复制它

Q2-你可以使用一个迭代要经过设置并打印其项目:

set<Point>::iterator mySetIterator; 

for (mySetIterator = s_p2.begin(); mySetIterator != s_p2.end(); mySetIterator++) 
{ 
    //print mySetIterator, where mySetIterator is a pointer to the n-th value of your set 
    cout<<(*mySetIteartor); 
} 
+0

但是我得到这个错误Assn3.cpp:166:12:错误:'std :: cout << mySetIterator.std :: _ Rb_tree_const_iterator <_Tp> ::运算符* [与_TP =点,的std :: _ Rb_tree_const_iterator <_Tp> ::参考=常数点和()” –

+0

如果你已经覆盖你的运营商<<,记得要取消引用mySetIterator,因为它是一个指针cout << * mySetIterator; –

+1

'mySetIterator'不是一个指针:它是一个迭代器。如果它是一个指针,那么运算符'''会愉快地打印它指向的地址。 – Gorpik

-2

Q1: If i do this will my set have only 1 item or multiple items of temp_p

由于您使用的一组容器,它被定义为存储唯一键,你会得到每个点的唯一值。如果你使用multiset,那么你会有多个值。

Q2 How can I print out the values inside the set?

我同意juanchopanza写了什么。

顺便说一句:看来,通过查看你的代码,你读的每个点,插入的值是[3 4等。这是你打算做什么?