【发布时间】:2011-06-03 13:22:44
【问题描述】:
我想将一个二维向量逐行推入哈希表中,然后在哈希表中搜索一行(向量)并希望能够找到它。我想做类似的事情
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main(){
std::set < vector<int> > myset;
vector< vector<int> > v;
int k = 0;
for ( int i = 0; i < 5; i++ ) {
v.push_back ( vector<int>() );
for ( int j = 0; j < 5; j++ )
v[i].push_back ( k++ );
}
for ( int i = 0; i < 5; i++ ) {
std::copy(v[i].begin(),v[i].end(),std::inserter(myset)); // This is not correct but what is the right way ?
// and also here, I want to search for a particular vector if it exists in the table. for ex. myset.find(v[2].begin(),v[2].end()); i.e if this vector exists in the hash table ?
}
return 0;
}
我不确定如何在集合中插入和查找向量。因此,如果有人可以指导我,那将很有帮助。谢谢
更新:
当我意识到std::set 不是哈希表时,我决定使用unordered_map,但我应该如何在其中插入和查找元素:
#include <iostream>
#include <tr1/unordered_set>
#include <iterator>
#include <vector>
using namespace std;
typedef std::tr1::unordered_set < vector<int> > myset;
int main(){
myset c1;
vector< vector<int> > v;
int k = 0;
for ( int i = 0; i < 5; i++ ) {
v.push_back ( vector<int>() );
for ( int j = 0; j < 5; j++ )
v[i].push_back ( k++ );
}
for ( int i = 0; i < 5; i++ )
c1.insert(v[i].begin(),v[i].end()); // what is the right way? I want to insert vector by vector. Can I use back_inserter in some way to do this?
// how to find the vectors back?
return 0;
}
【问题讨论】:
-
我编辑了最后一行。即使对于此代码,我也会在插入器行中遇到错误。我该怎么办?
-
我没有看到哈希表。你在说
std::set吗? -
STL 集内的 STL 向量内的 STL 向量。没有上下文,这似乎是糟糕的设计。如果你解释你试图解决的问题,你肯定会得到更好的建议。
-
std::set不是哈希表。这将是 C++0x 标准草案中的std::unordered_map或std::unordered_set。 -
我明白了。我假设 std::set 是一个哈希表。我想要的只是在哈希表的每个桶中插入一个向量,然后在代码中搜索该向量。就像插入和查找元素一样。
标签: c++ vector hashtable unordered-set