-
15-10-2019 - |
题
我想通过行将2D向量推入哈希表,然后在哈希表中搜索一行(向量),并希望能够找到它。我想做类似的事情
#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::insert
, ,ala
myset.insert(v.begin(), v.end());
为了查找,使用 std::set::find
翼
std::set < vector<int> >::iterator it = myset.find(v[1]);
工作示例:
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
typedef vector<int> int_v_t;
typedef set<int_v_t> set_t;
set_t myset;
// this creates 5 items
typedef vector<int_v_t> vec_t;
vec_t v(5);
int k = 0;
for(vec_t::iterator it(v.begin()), end(v.end()); it != end; ++it)
{
for (int j = 0; j < 5; j++)
it->push_back(k++);
}
// this inserts an entry per vector into the set
myset.insert(v.begin(), v.end());
// find a specific vector
set_t::iterator it = myset.find(v[1]);
if (it != myset.end()) cout << "found!" << endl;
return 0;
}
其他提示
使用 std::copy
插入一组:
#include <algorithm>
#include <iterator>
#include <vector>
std::vector<int> v1;
// Fill in v1 here
std::vector<int> v2;
std::copy(v1.begin(), v1.end(), std::back_inserter<std::vector<int> >(v2));
您也可以使用 std::vector
分配,插入或复制构造函数要执行相同的操作。
您正在使用 std::set
在此示例中。一组没有查找方法。您只需迭代每个项目的操作。如果您想使用哈希/键查找特定的项目,则需要查看诸如此类的数据结构 std::map
.
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 ?
}
这是不正确的,因为您正在尝试将向量向量向量的每个向量的整数复制到集合中。您的意图和集合的类型表明您希望将5个向量插入您的集合中。然后,您只需执行此操作(无循环):
std::copy(v.begin(), v.end(), std::inserter(myset));
不隶属于 StackOverflow