2012-11-14 92 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等。這是你打算做什麼?