To find the index of a specified element in a list in C++, you can use the std::find
algorithm from the
header.
In this example,
myList
with some elements.std::find
algorithm to search for the specified element in the list.std::find
returns an iterator pointing to the first occurrence of the element. We then calculate the index using std::distance
.std::find
returns the end iterator of the list.#include <iostream>
#include <list>
#include <algorithm>
int main() {
std::list<int> myList = {10, 20, 30, 40, 50};
int searchElement = 40;
auto it = std::find(myList.begin(), myList.end(), searchElement);
if (it != myList.end()) {
int index = std::distance(myList.begin(), it);
std::cout << "Index of element is: " << index << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
Index of element is: 3
In this example,
myList
with some string elements.std::find
algorithm to search for the specified string in the list.std::find
returns an iterator pointing to the first occurrence of the string. We then calculate the index using std::distance
.std::find
returns the end iterator of the list.#include <iostream>
#include <list>
#include <algorithm>
#include <string>
int main() {
std::list<std::string> myList = {"apple", "banana", "cherry", "date", "elderberry"};
std::string searchElement = "cherry";
auto it = std::find(myList.begin(), myList.end(), searchElement);
if (it != myList.end()) {
int index = std::distance(myList.begin(), it);
std::cout << "Index of element is: " << index << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
Index of element is: 2
In this tutorial, we learned How to get the Index of Specified Element in a List in C++ language with well detailed examples.