返回vector中元素的下標(biāo):
```c++
#include
#include
int main() {
??std::vector v = {10, 20, 30, 40, 50};
??// 返回元素為40的下標(biāo)
??auto it = std::find(v.begin(), v.end(), 40);
??int index = std::distance(v.begin(), it);
??std::cout << "Index of 40: " << index << std::endl;
??// 返回元素為20的下標(biāo)
??it = std::find(v.begin(), v.end(), 20);
??index = std::distance(v.begin(), it);
??std::cout << "Index of 20: " << index << std::endl;
??return 0;
}
```
輸出:
```
Index of 40: 3
Index of 20: 1
```
這里使用了`std::find`函數(shù)尋找元素的迭代器,并使用`std::distance`函數(shù)計(jì)算該迭代器與vector起始迭代器之間的距離,即該元素在vector中的下標(biāo)。
標(biāo)簽: