Find Element in Vector

Find Element in Vector

Easy C++ STL 54 views
Explanation Complexity

Problem Statement

Search for element in vector using find().
Real Life: Searching for item in list.

Input Format

Search for element in vector using find().
Real Life: Searching for item in list.

Output Format

• Found at index i
OR

• Not Found

Example

5
10 20 30 40 50
30
Found at index 2

Constraints

• n ≥ 1

• Use find() from

• 0-based indexing

Concept Explanation

find() searches for a value in a vector.
It returns an iterator to the element if found,
otherwise it returns end().

Step-by-Step Explanation

1.Read n and the vector elements.

2.Read the value x to search.

3.Call find(vec.begin(), vec.end(), x).

4.If returned iterator is not vec.end():

• Element is found.

• Index = iterator − vec.begin().

5.Else:

• Element is not found.

Concept Explanation

find() searches for a value in a vector.
It returns an iterator to the element if found,
otherwise it returns end().

Step-by-Step Explanation

1.Read n and the vector elements.

2.Read the value x to search.

3.Call find(vec.begin(), vec.end(), x).

4.If returned iterator is not vec.end():

• Element is found.

• Index = iterator − vec.begin().

5.Else:

• Element is not found.

Input / Output Format

Input Format
Search for element in vector using find().
Real Life: Searching for item in list.
Output Format
• Found at index i
OR

• Not Found
Constraints
• n ≥ 1

• Use find() from

• 0-based indexing

Examples

Input:
5 10 20 30 40 50 30
Output:
Found at index 2

Example Solution (Public)

C++
void stl_q5_find_element() {
    vector<int> numbers = {10, 20, 30, 40, 50};
    int searchValue = 30;
    
    auto it = find(numbers.begin(), numbers.end(), searchValue);
    
    if(it != numbers.end()) {
        int position = it - numbers.begin();
        cout << "Element " << searchValue << " found at position " << position << endl;
    } else {
        cout << "Element not found" << endl;
    }
}

Official Solution Code

void stl_q5_find_element() {
    vector<int> numbers = {10, 20, 30, 40, 50};
    int searchValue = 30;
    
    auto it = find(numbers.begin(), numbers.end(), searchValue);
    
    if(it != numbers.end()) {
        int position = it - numbers.begin();
        cout << "Element " << searchValue << " found at position " << position << endl;
    } else {
        cout << "Element not found" << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.