[英]c++: how to determine if a variable is a vector element
我有一個方法,我想根據傳遞的變量是否是向量的元素來執行不同的方法,例如:
void method(int a){
if (/*a is an element of a vector*/) //do one thing
else //do another thing
}
然后在主要:
vector<int> a;
a.pushback(1);
int b = 1;
method(a[0]); // does one thing
method(b); // does the other thing
最簡單的方法是什么?
好吧,在所有情況下這都是不可能的,因為它實際上需要您的函數查看其執行方式 ,而C ++中沒有這樣的東西。 令人討厭的eval()浮現在腦海。
但是在某些情況下,當向量是全局實體時,可以通過鏈接而不是值傳遞變量。 然后,您可以檢查它是否適合所需向量的開始和結束之間的空間。 這是完成的方式(雖然尚未測試,但應該可以工作)
vector<int> v;
//fill it somewhere somehow
void method(int& a)
{
int* beg = v.data();
int* end = beg + v.size();
int* val = &a;
if ((val >= beg) && (val < end))
{
//it is a part of vector
}
else
{
//it is not a part of vector
{
}
問題是您真的不應該這樣做...正如評論中的人所說,它看起來像是XY問題。
一個int
是一個int
。 一個int
的脖子上沒有貼標簽,告訴每個人它的來源。 將int
傳遞給函數時,沒有任何東西可以指定int
起源。
您應該以此為契機學習迭代器,並實現采用
void method(int);
用於參數或
void method(std::vector<int>::iterator iter);
參數(或者可能是const_iterator
),並通過將迭代器傳遞給向量中的int
來調用替代method()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.