【问题标题】:set of tuples of items in grocery杂货店中物品的元组
【发布时间】:2020-11-02 07:25:04
【问题描述】:

我正在做一个给定项目名称、价格和数量向量的问题,我必须找出组合时它们中有多少重复项。所以我确实通过使用元组集解决了这个问题,但后来我想到了解包并打印它们。 这是我的代码:

#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<string> name{"ball", "bat", "glove", "glove","glove"};
    vector<int> price{2,3,1,2,1};
    vector<int> w{2,5,1,1,1};
set<tuple<string,int,int>> s;
for(int i = 0; i < name.size(); i++){
    s.insert({name[i],price[i],w[i]});
}
for(int i = 0; i < s.size(); i++){
    string st;
    int p; 
    int we;
    tie(st,p,we) = s[i]; **statement**
    cout<<st<<" "<<p<<" "<<we<<'\n';
}
cout<<name.size() - s.size();
return 0;
}

但是语句行中有错误。拆不开。需要帮忙。谢谢。

【问题讨论】:

  • 错误是...?

标签: set tuples c++14 c++17


【解决方案1】:

很遗憾,您无法使用 tie 解包元组。 虽然,如果您使用的是 c++17,则可以使用这样的结构绑定(请原谅​​缩进):

#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<string> name{"ball", "bat", "glove", "glove","glove"};
    vector<int> price{2,3,1,2,1};
    vector<int> w{2,5,1,1,1};
     set<tuple<string,int,int>> s;
for(int i = 0; i < name.size(); i++){
    s.insert({name[i],price[i],w[i]});
}

for(auto tup : s){
    auto [a, b, c] = tup;
    cout<<a<<" "<<b<<" "<<c<<'\n';
}
cout<<name.size() - s.size();
return 0;
}

在 C++11/14 中,您可以考虑直接打印它:

cout << get<0>(tup) << " " << get<1>(tup) << " " << get<2>(tup) << endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多