英文:
Is there a method/function in c++ which later constant parameters are based on the first ones?
问题
The constant parameter list seems to be error. I want to use the last parameter based on the 1st one
#include<iostream>
#include<vector>
using namespace std;
template<class T>
int ExistIndex(const vector<T> v, T obj, int start = 0, int end = v.size() - 1)
{
//The last parameter is the problem
//Finds the index where obj exists in the vector. If it does not
// -1 is returned. does not check for bounds
for (int i = start; i <= end; i++)
{
//Finding the object
if (v[i] == obj) return i;
}
return -1;
}
int main()
{
//Executing
vector<int> v1 = {1, 2, 3, 4};
int l = ExistIndex(v1, 3);// Although this compiles
cout << endl;
system("pause");
return 0;
}
(Note: I didn't translate the code part as requested.)
英文:
The constant parameter list seems to be error. I want to use the last parameter based on the 1st one
#include<iostream>
#include<vector>
using namespace std;
template<class T>
int ExistIndex(const vector<T> v, T obj, int start = 0, int end = v.size() - 1)
{
//The last parameter is the problem
//Finds the index where obj exists in the vector. If it does not
// -1 is returned. does not check for bounds
for (int i = start; i <= end; i++)
{
//Finding the object
if (v[i] == obj) return i;
}
return -1;
}
int main()
{
//Executing
vector<int> v1 = {1, 2, 3, 4}
int l = ExistIndex(v1, 3);// Although this compiles
cout << endl;
system("pause");
return 0;
}
答案1
得分: 3
你所写的代码无法通过编译。我看到以下错误:
prog.cpp:6:67: error: local variable ‘v’ may not appear in this context
int ExistIndex(const vector<T> v, T obj, int start = 0, int end = v.size() - 1)
然而,要实现这个功能,我会使用较少参数的重载函数,然后让它调用你的“真实”函数(这实际上是默认参数在幕后所做的):
template<class T>
int ExistIndex(const vector<T> v, T obj, int start = 0)
{
return ExistIndex(v, obj, start, v.size() - 1);
}
英文:
What you've written does not compile for me. I see:
prog.cpp:6:67: error: local variable ‘v’ may not appear in this context
int ExistIndex(const vector<T> v, T obj, int start = 0, int end = v.size() - 1)
^
However, to accomplish this, I'd overload the function with less arguments and have that call your "real" function (this is what default parameters are doing under the hood anyways):
template<class T>
int ExistIndex(const vector<T> v, T obj, int start = 0)
{
return ExistIndex(v, obj, start, v.size() - 1);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论