C++ 从属范围;需要在前面输入typename;
我想创建一个模板,如下所示。我想从vectorC++ 从属范围;需要在前面输入typename;,c++,templates,vector,C++,Templates,Vector,我想创建一个模板,如下所示。我想从vectorvec1中删除项目列表。我要删除的项目的索引存储在index\u list中 #include <vector> using namespace std; template <typename a_type> bool vector_remove(vector< a_type > & vec1, vector< int > index_list) { //index_list is
vec1
中删除项目列表。我要删除的项目的索引存储在index\u list
中
#include <vector>
using namespace std;
template <typename a_type>
bool vector_remove(vector< a_type > & vec1, vector< int > index_list)
{
//index_list is sorted in order from small to large.
if(index_list.size() > vec1.size())
{
cout << "ERROR in 'vector_remove()': index_list is longer than vec1."<<endl;
return false;
}
if(index_list.size() == vec1.size())
{
vec1.clear();
return true;
}
vector< int >::iterator ind_pt = index_list.begin();
vector< a_type >::iterator vec1_pre = vec1.begin();
vector< a_type >::iterator vec1_pos = vec1.begin();
int vec1_ind = 0;
while(ind_pt != index_list.end() && vec1_pos != vec1.end())
{
if(*ind_pt == vec1_ind)
{
ind_pt ++;
vec1_pos ++;
vec1_ind ++;
}
else if( *ind_pt > vec1_ind )
{
*(vec1_pre) = *(vec1_pos);
vec1_pos ++;
vec1_pre ++;
vec1_ind ++;
}
else
{
cout << "ERROR in 'vector_remove'." <<endl;
return false;
}
}
while(vec1_pos != vec1.end())
{
*(vec1_pre) = *(vec1_pos);
vec1_pos ++;
vec1_pre ++;
}
// the above codes are to put all the rejected elements to the end of the vec1.
// pop back all the rejected elements.
while(vec1_pre != vec1.end() )
{
vec1.pop_back();
}
return true;
}
#包括
使用名称空间std;
模板
bool vector\u remove(vector&vec1,vector索引列表)
{
//索引列表按从小到大的顺序排序。
if(index_list.size()>vec1.size())
{
cout::迭代器vec1_pos=vec1.begin();
int vec1_ind=0;
而(ind_pt!=index_list.end()&vec1_pos!=vec1.end())
{
如果(*ind\u pt==vec1\u ind)
{
ind_pt++;
vec1_pos++;
vec1_ind++;
}
否则如果(*ind\u pt>vec1\u ind)
{
*(vec1_-pre)=*(vec1_-pos);
vec1_pos++;
vec1_pre++;
vec1_ind++;
}
其他的
{
cout::迭代器vec1_pos=vec1.begin();
^
my_vector.h:22:29:错误:在“vec1_pos”之前应为“;”
vector:迭代器vec1_pos=vec1.begin();
^
my_vector.h:24:38:错误:“vec1_pos”未在此作用域中声明
而(ind_pt!=index_list.end()&vec1_pos!=vec1.end())
^
my_vector.h:34:6:错误:“vec1_pre”未在此范围内声明
*(vec1_-pre)=*(vec1_-pos);
^
my_vector.h:45:8:错误:“vec1_pos”未在此作用域中声明
while(vec1_pos!=vec1.end())
^
my_vector.h:47:5:错误:“vec1_pre”未在此作用域中声明
*(vec1_-pre)=*(vec1_-pos);
^
my_vector.h:54:8:错误:“vec1_pre”未在此范围内声明
while(vec1_pre!=vec1.end())
有人能帮我解决这个问题吗?编译器说
my_vector.h:21:2:错误:之前需要'typename'
“std::vector::iterator”,因为“std::vector”是
从属范围
所以你需要写作
typename vector< a_type >::iterator vec1_pre = vec1.begin();
typename vector< a_type >::iterator vec1_pos = vec1.begin();
错误消息告诉您需要什么。请将typename关键字放在这些行的前面,并将
typename
放在这些行的前面。@ooga好的。很好,它可以工作。这太棒了。但是您能告诉我什么时候应该将“typename”放在行的前面吗?@tqjustc,当它是一个依赖于模板参数的声明时。我们当然可以告诉您U
typename vector< a_type >::iterator vec1_pre = vec1.begin();
typename vector< a_type >::iterator vec1_pos = vec1.begin();
auto vec1_pre = vec1.begin();
auto vec1_pos = vec1.begin();