[英]Storing (x, y) Coordinates with set
我需要幫助在一組中存儲(x,y)坐標組。 我存儲的方式是
set<int> s;
s.insert( (1, 1) );
s.insert( (1, 3) );
s.insert( (3, 1) );
s.insert( (3, 3) );
for (auto x: s) {
cout << x << endl;
}
但它不會打印出(1,1),(1,3)....而是打印出1,3。
我對c ++很新,所以如果有人能給我建議如何用一組存儲這些值,我將不勝感激!
您的代碼會發生以下情況:
s
的類型為std::set<int>
,因此適用於存儲int
類型的變量。
調用函數std::set<int>::insert
需要一個int
類型的參數。 如果你做s.insert((1, 3))
你實際上不插入一對但使用逗號運算符 。 它的工作原理是這樣的:在表達a, b
,表達a
進行評價時,則表達b
被評估和表達式的結果b
被返回作為整個表達式的結果。 您可以在此處閱讀更多相關信息: 逗號運算符如何工作 。
因此, s.insert((1, 3))
導致s.insert(3)
並且將3
插入到s
。
要實現所需的行為,可以使用頭utility
定義的std::pair
。 可能的方法如下:
std::set<std::pair<int, int>> s;
s.insert(std::make_pair(1, 1));
s.insert(std::make_pair(1, 3));
s.insert(std::make_pair(3, 1));
s.insert(std::make_pair(3, 3));
for (const auto& e : s)
std::cout << "(" << e.first << ", " << e.second << ") ";
輸出:
(1,1)(1,3)(3,1)(3,3)
插入對的其他語法如下,使用初始化列表:
s.insert({1, 3});
如果你想構建對而不是構造和插入它們,你可以使用std::set::emplace
,如下所示:
s.emplace(1, 3);
我認為你的意思是使用對,對是一對夫妻一起耦合一對值,可以轉換為坐標x,y
set<std::pair<int,int>> s;
s.insert({ 1, 1 });
s.insert({ 1, 3 });
s.insert({ 3, 1 });
s.insert({ 3, 3 });
for (auto x : s) {
std::cout << x.first<< " "<<x.second << std::endl;
}
// to print the first & the last element
auto start = s.begin();
auto last=s.rbegin();
std::cout << start->first << " " << start->second << " " << last->first << " " << last->second<<'\n';
// for the nth element
int n=2;
auto nelement=std::next(s.begin(), n);
std::cout<<nelement->first<<" "<<nelement->second;
set<int>
只能存儲一個 int,而不能存儲兩個 (在單個insert
操作中)。 如果你寫s.insert( (1, 3) );
你顯然試圖插入2,這是行不通的。 它似乎以某種方式工作,但實際上語法對你來說是一個討厭的伎倆!
在這種情況下(1, 3)
表達式(1, 3)
使用逗號運算符 ,它的作用是:計算1(它是,好吧,1), 扔掉它 ,然后計算3,這顯然是3,這個是返回的:3。所以你的陳述實際上等同於s.insert(3);
。 Taht是你沒有得到編譯錯誤的原因。 但顯然這不是你想要的。
要解決此問題,您必須使用一次存儲兩個值的集合。 有一種數據類型,稱為std :: pair !
所以你可以聲明它
set<std::pair<int,int>> s;
並將數據插入其中
s.insert({1, 3});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.