在C++中,可以使用以下方法在vector<float>中查找特定的第一个和最后一个索引:
int main() {
std::vector<float> numbers = {1.2, 3.4, 5.6, 7.8, 9.0, 3.4, 5.6};
float target = 3.4;
auto it = std::find(numbers.begin(), numbers.end(), target);
if (it != numbers.end()) {
int index = std::distance(numbers.begin(), it);
std::cout << "First index of " << target << ": " << index << std::endl;
} else {
std::cout << "Target value not found." << std::endl;
}
return 0;
}
```
int main() {
std::vector<float> numbers = {1.2, 3.4, 5.6, 7.8, 9.0, 3.4, 5.6};
float target = 3.4;
auto it = std::find(std::make_reverse_iterator(numbers.end()), std::make_reverse_iterator(numbers.begin()), target);
if (it != std::make_reverse_iterator(numbers.begin())) {
int index = std::distance(numbers.begin(), --it.base());
std::cout << "Last index of " << target << ": " << index << std::endl;
} else {
std::cout << "Target value not found." << std::endl;
}
return 0;
}
```
int main() {
std::vector<float> numbers = {1.2, 3.4, 5.6, 7.8, 9.0, 3.4, 5.6};
float target = 3.4;
std::vector<int> indices;
for (int i = 0; i < numbers.size(); i++) {
if (numbers[i] == target) {
indices.push_back(i);
}
}
if (!indices.empty()) {
std::cout << "Indices of " << target << ": ";
for (int index : indices) {
std::cout << index << " ";
}
std::cout << std::endl;
} else {
std::cout << "Target value not found." << std::endl;
}
return 0;
}
```
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云