在std :: set中插入对是不一致的(不识别<pair> .second)

时间:2016-04-23 10:47:28

标签: c++ c++11 std stdset

如果添加条件,此代码的执行方式不同:

第一种情况:

public class Your_Adapter extends BaseAdapter{

    private Context mContext;
    private GetClickedItem mGetClickedItem;
    Holder holder;

    // Constructor
    public Your_Adapter(Context context, GetClickedItem itemclickreference) {
        mContext = context;
        this.mGetClickedItem = itemclickreference;
    }

    public int getCount() {
        return your_data_size;
    }

    public Object getItem(int position) {
        return your_data.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

       holder = new Holder();

       if (convertView == null) {
           LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
           convertView = mInflater.inflate(R.layout.xml_layout, null);

           holder.mButton = (Button) convertView.findViewById(R.id.button);

           convertView.setTag(holder);

       }else {
           holder = (Holder) convertView.getTag();
       } 

       holder.mButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mGetClickedItem.getPostID(position, your_data.get(position));
            }
       });

        return convertView;
    }

    public class Holder{
        Button mButton;
    }

    public interface GetClickedItem{
       public void getPostID(int position, String any_other_data);
    }
}

输出

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

struct comp
{
    bool operator()(pair<int,pair<int,int> > a, pair<int,pair<int,int> > b)
    {
        return a.first>b.first;
    }
};

int main()
{
    set<pair<int,pair<int,int>>,comp> s;
    auto d = s.insert({4,{6,10}});
    cout<<(d.first)->first<<" "<<(d.first)->second.first<<" "<<(d.first)->second.second<<endl;
    d = s.insert({4,{0,4}});
    cout<<(d.first)->first<<" "<<(d.first)->second.first<<" "<<(d.first)->second.second<<endl;
}

第二种情况:(条件为.second)

4 6 10
4 6 10

输出:

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

struct comp
{
    bool operator()(pair<int,pair<int,int> > a, pair<int,pair<int,int> > b)
    {
        if(a.first==b.first)
            return a.second.first<b.second.first;
        return a.first>b.first;
    }
};

int main()
{
    set<pair<int,pair<int,int>>,comp> s;
    auto d = s.insert({4,{6,10}});
    cout<<(d.first)->first<<" "<<(d.first)->second.first<<" "<<(d.first)->second.second<<endl;
    d = s.insert({4,{0,4}});
    cout<<(d.first)->first<<" "<<(d.first)->second.first<<" "<<(d.first)->second.second<<endl;
}

为什么设置在第一种情况下不添加不同的对?我认为额外的条件只决定顺序,并没有区分元素。

1 个答案:

答案 0 :(得分:3)

您的第一个比较器仅考虑该对中的第一项。当您尝试插入第二对时,它被认为等于已插入的对,因此未插入。

相反,您将返回已插入集合中的对象,这是预期的行为。

请记住,根据定义,一个集合只有一个特定对象的实例,而你的比较器可以帮助它说明两个对象如何相互比较。