有没有办法按照在c ++中创建的顺序将键存储在hashmap中?

时间:2016-10-21 13:07:48

标签: c++ stl hashmap

我想编写一个程序,在数组中存储2个数字的总和,并按生成顺序检索它。我知道map会按排序顺序存储密钥。 Unordered_map按顺序存储密钥,该顺序绝对不是基于生成顺序。

有什么方法可以使用STL来获得我想要的c ++? 以下是我的程序代码。我需要找到一个包含4个数字的数组,其中A + B = C + D,这样所有数字都是唯一的,并按字典顺序排序。

数组= 1 3 3 3 3 2 2 我应该得到0 1 6 7作为输出,但我得到1 5 2 6。

vector<int> Solution::equal(vector<int> &A) {
vector<int> result;
unordered_map<int,vector<vector<int>>> hash;
int n = A.size();

for(int i = 0; i < n ; i++) {
  for(int j = i+1; j < n; j++) {
      int sum = A[i] + A[j];
      vector<int> temp{i,j};
      if (hash.find(sum) != hash.end()) {
        hash[sum].push_back(temp);
      }
      else
        hash.insert(make_pair(sum,vector<vector<int>>{temp}));
  }
}

for(unordered_map<int,vector<vector<int>>>::iterator it=hash.begin(); it != hash.end(); it++) {
  int size = it->second.size();
  bool found = 0;
  if( size > 1) {

    for(int i = 1; i < size; i++) {
        cout<<it->first<<" ";
        if (it->second[0][0] == it->second[i][0] || it->second[0][1] == it->second[i][0] || it->second[0][1] == it->second[i][1]) continue;
        result.push_back(it->second[0][0]);
        result.push_back(it->second[0][1]);
        result.push_back(it->second[i][0]);
        result.push_back(it->second[i][1]);
        found = 1;
         break;
    }
    if (found) break;
  }
}
return result; 
}

0 个答案:

没有答案
相关问题