Как найти номер элемента в векторе

Something like this, I think. find_if_counted.hpp:

#ifndef FIND_IF_COUNTED_HPP
#define FIND_IF_COUNTED_HPP

#include <algorithm>

namespace find_if_counted_impl
{
    template <typename Func>
    struct func_counter
    {
        explicit func_counter(Func& func, unsigned &count) :
        _func(func),
        _count(count)
        {
        }

        template <typename T>
        bool operator()(const T& t)
        {
            ++_count;

            return _func(t);
        }

    private:
        Func& _func;
        unsigned& _count;
    };
}

// generic find_if_counted,
// returns the index of the found element, otherwise returns find_if_not_found
const size_t find_if_not_found = static_cast<size_t>(-1);

template <typename InputIterator, typename Func>
size_t find_if_counted(InputIterator start, InputIterator finish, Func func)
{
    unsigned count = 0;
    find_if_counted_impl::func_counter<Func> f(func, count);

    InputIterator result = find_if(start, finish, f);

    if (result == finish)
    {
        return find_if_not_found;
    }
    else
    {
        return count - 1;
    }
}

#endif

Example:

#include "find_if_counted.hpp"
#include <cstdlib>
#include <iostream>
#include <vector>

typedef std::vector<int> container;

int rand_number(void)
{
    return rand()  % 20;
}

bool is_even(int i)
{
    return i % 2 == 0;
}

int main(void)
{
    container vec1(10);
    container vec2(10);

    std::generate(vec1.begin(), vec1.end(), rand_number);
    std::generate(vec2.begin(), vec2.end(), rand_number);

    unsigned index = find_if_counted(vec1.begin(), vec1.end(), is_even);

    if (index == find_if_not_found)
    {
        std::cout << "vec1 has no even numbers." << std::endl;
    }
    else
    {
        std::cout << "vec1 had an even number at index: " << index <<
            " vec2's corresponding number is: " << vec2[index] << std::endl;
    }
}

Though I feel like I’m doing something silly… :X Any corrections are welcome, of course.

В этом посте мы обсудим, как найти индекс первого вхождения заданного элемента в vector в C++.

1. Использование std::find с std::distance функция

Самое простое решение — использовать std::find алгоритм, определенный в <algorithm> заголовок. Идея состоит в том, чтобы получить индекс, используя std::distance на итераторе, возвращенном std::find, который указывает на найденное значение. Мы также можем применить арифметику указателя к итераторам. Следовательно - оператор тоже будет работать.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

#include <iostream>

#include <vector>

#include <algorithm>

int main()

{

    std::vector<int> v = { 7, 3, 6, 2, 6 };

    int key = 6;

    std::vector<int>::iterator itr = std::find(v.begin(), v.end(), key);

    if (itr != v.cend()) {

        std::cout << «Element present at index « << std::distance(v.begin(), itr);

    }

    else {

        std::cout << «Element not found»;

    }

    return 0;

}

Скачать  Выполнить код

результат:

Element present at index 2

2. Использование std::find_if с std::distance функция

Мы также можем использовать стандартный алгоритм std::find_if, который принимает предикат. Это рекомендуемый подход, если поиск должен удовлетворять определенным условиям. Например, найти индекс первой строки, начинающейся с некоторого символа в векторе строк.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

#include <iostream>

#include <vector>

#include <algorithm>

struct compare

{

    int key;

    compare(int const &i): key(i) {}

    bool operator()(int const &i) {

        return (i == key);

    }

};

int main()

{

    std::vector<int> v = { 7, 3, 6, 2, 6 };

    int key = 6;

    auto itr = std::find_if(v.cbegin(), v.cend(), compare(key));

    if (itr != v.cend()) {

        std::cout << «Element present at index « << std::distance(v.cbegin(), itr);

    }

    else {

        std::cout << «Element not found»;

    }

    return 0;

}

Скачать  Выполнить код

результат:

Element present at index 2

3. Наивное решение

Наконец, мы можем написать собственную процедуру для этого, как показано ниже:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

#include <iostream>

#include <vector>

#include <algorithm>

int main()

{

    std::vector<int> v = { 7, 3, 6, 2, 6 };

    int key = 6;

    bool found = false;

    for (int i = 0; i < v.size(); i++)

    {

        if (v[i] == key)

        {

            std::cout << «Element present at index « << i;

            found = true;

            break;

        }

    }

    if (!found) {

        std::cout << «Element not found»;

    }

    return 0;

}

Скачать  Выполнить код

результат:

Element present at index 2

Вот и все, что касается нахождения индекса элемента в векторе в C++.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given a vector V consisting of N integers and an element K, the task is to find the index of element K in the vector V. If the element does not exist in vector then print -1.

    Examples: 

    Input: V = {1, 45, 54, 71, 76, 17}, K = 54 
    Output:
    Explanation : 
    The index of 54 is 2, hence output is 2.
    Input: V = {3, 7, 9, 11, 13}, K = 12 
    Output: -1 

    Approach: 
    Follow the steps below to solve the problem:  

    • find(): Used to find the position of element in the vector.
    • Subtract from the iterator returned from the find function, the base iterator of the vector .
    • Finally return the index returned by the subtraction.

    Below is the implementation of the above approach :  

    C++

    #include <bits/stdc++.h>

    using namespace std;

    void getIndex(vector<int> v, int K)

    {

        auto it = find(v.begin(), v.end(), K);

        if (it != v.end()) 

        {

            int index = it - v.begin();

            cout << index << endl;

        }

        else {

            cout << "-1" << endl;

        }

    }

    int main()

    {

        vector<int> v = { 1, 45, 54, 71, 76, 17 };

        int K = 54;

        getIndex(v, K);

        return 0;

    }

    Time Complexity: O(N) 
    Auxiliary Space: O(1)

    Last Updated :
    10 Jan, 2023

    Like Article

    Save Article

    In this article we will different ways to find an element in vector and get its index.

    Suppose we have a vector of int i.e.

    Advertisements

    std::vector<int> vecOfNums = { 12, 45, 54, 33, 2, 7, 8, 22, 43, 19 };

    Now we want to find if number 22 exists in vector ? If yes then what’s its index or position in the vector ?

    std::vector doesn’t provides any direct function to check if an element exists in vector or not. So let’s see how to do that using STL Algorithms.

    Frequently Asked:

    • vector::push_back() function in C++
    • Convert a String to a Vector of Bytes in C++
    • Importance of Constructors while using User Defined Objects with std::vector
    • How to fill a vector with random numbers in C++

    Finding an element in vector using STL Algorithm std::find()

    Basically we need to iterate over all the elements of vector and check if given elements exists or not.
    This can be done in a single line using std::find i.e.

    // Check if element 22 exists in vector
    std::vector<int>::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22);

    It accepts a range and an element to search in the given range. If element is found then it returns an iterator to the first element in the given range that’s equal to given element, else it returns an end of the list.

    if (it != vecOfNums.end())
    	std::cout << "Element Found" << std::endl;
    else
    	std::cout << "Element Not Found" << std::endl;
    

    If element is found then we can get its index from the iterator i.e.

    // Get index of element from iterator
    int index = std::distance(vecOfNums.begin(), it);

    But in practical, we will not have vector of integers always. So, let’s create a generic function for this.

    Generic function to find an element in vector of any type

    Let’s create a generic function to search an element in any type of vector i.e.

    /*
    Generic function to find an element in vector and also its position.
    It returns a pair of bool & int i.e.
    
    bool : Represents if element is present in vector or not.
    int : Represents the index of element in vector if its found else -1
    
    */
    template < typename T>
    std::pair<bool, int > findInVector(const std::vector<T>  & vecOfElements, const T  & element)
    {
    	std::pair<bool, int > result;
    
    	// Find given element in vector
    	auto it = std::find(vecOfElements.begin(), vecOfElements.end(), element);
    
    	if (it != vecOfElements.end())
    	{
    		result.second = distance(vecOfElements.begin(), it);
    		result.first = true;
    	}
    	else
    	{
    		result.first = false;
    		result.second = -1;
    	}
    
    	return result;
    }
    
    

    This function tells if given element exists in vector and if yes then it also return its position in the vector.

    Let’s use this function to find an element in vector i.e.

    std::pair<bool, int> result = findInVector<int>(vecOfNums, 45);
    
    if (result.first)
    	std::cout << "Element Found at index : " << result.second <<std::endl;
    else
    	std::cout << "Element Not Found" << std::endl;
    

    Finding an element by custom comparator using std::find_if()

    Instead of directly searching by value in the vector , we can search by custom logic too.

    Like, in a vector of int check if any multiple of 3 exists i.e.

    // Check if any multiple of 3  exists in vector using lambda function as comparator
    
    std::vector<int>::iterator it2 = std::find_if(vecOfNums.begin(), vecOfNums.end(), [](const int & val){
    																							if (val % 3 == 0)
    																								return true;
    																							return false;
    																						});
    
    if (it != vecOfNums.end())
    	std::cout << "Multiple of 3 Found : " << *it2 << std::endl;
    else
    	std::cout << "Multiple of 3 Not Found" << std::endl;
    

    Finding an element in vector using C++11 Range Based for loop

    We can also iterate over the vector using range based for loop and check if element exists or not.

    bool found = false;
    // Iterate over all elements in Vector
    for (auto & elem : vecOfNums)
    {
    	if (elem == 22)
    	{
    		found = true;
    		break;
    	}
    }
    if(found)
    	std::cout << "Element Found" << std::endl;
    else
    	std::cout << "Element Not Found" << std::endl;
    

    Complete example is as follows,

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    /*
    Generic function to find an element in vector and also its position.
    It returns a pair of bool & int i.e.
    
    bool : Represents if element is present in vector or not.
    int : Represents the index of element in vector if its found else -1
    
    */
    template < typename T>
    std::pair<bool, int > findInVector(const std::vector<T>  & vecOfElements, const T  & element)
    {
    	std::pair<bool, int > result;
    
    	// Find given element in vector
    	auto it = std::find(vecOfElements.begin(), vecOfElements.end(), element);
    
    	if (it != vecOfElements.end())
    	{
    		result.second = distance(vecOfElements.begin(), it);
    		result.first = true;
    	}
    	else
    	{
    		result.first = false;
    		result.second = -1;
    	}
    
    	return result;
    }
    
    int main()
    {
    	std::vector<int> vecOfNums = { 12, 45, 54, 33, 2, 7, 8, 22, 43, 19 };
    
    	/*
    	Find an element in vector using std::find
    	*/
    
    	// Check if element 22 exists in vector
    	std::vector<int>::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22);
    
    	if (it != vecOfNums.end())
    	{
    		std::cout << "Element Found" << std::endl;
    
    		// Get index of element from iterator
    		int index = std::distance(vecOfNums.begin(), it);
    		std::cout <<"Index of element in vector : "<<index<<std::endl;
    	}
    	else
    	{
    		std::cout << "Element Not Found" << std::endl;
    	}
    
    	std::pair<bool, int> result = findInVector<int>(vecOfNums, 45);
    
    	if (result.first)
    		std::cout << "Element Found at index : " << result.second <<std::endl;
    	else
    		std::cout << "Element Not Found" << std::endl;
    
    
    	/*
    	 * Finding an element by custom comparator
    	 */
    
    
    // Check if any multiple of 3  exists in vector using lambda function as comparator
    
    std::vector<int>::iterator it2 = std::find_if(vecOfNums.begin(), vecOfNums.end(), [](const int & val){
    																							if (val % 3 == 0)
    																								return true;
    																							return false;
    																						});
    
    if (it != vecOfNums.end())
    	std::cout << "Multiple of 3 Found : " << *it2 << std::endl;
    else
    	std::cout << "Multiple of 3 Not Found" << std::endl;
    
    	/*
    		Find an element in vector using c++11 range based for loop
    	*/
    
    	bool found = false;
    	// Iterate over all elements in Vector
    	for (auto & elem : vecOfNums)
    	{
    		if (elem == 22)
    		{
    			found = true;
    			break;
    		}
    	}
    	if(found)
    		std::cout << "Element Found" << std::endl;
    	else
    		std::cout << "Element Not Found" << std::endl;
    
        return 0;
    }
    
    
    

    1. Use Custom Function to Find Element Index in Vector in C++
    2. Use std::find Algorithm to Find Element Index in Vector in C++
    3. Use std::find_if Algorithm to Find Element Index in Vector in C++

    Find Element Index in Vector in C++

    This article will explain several methods of how to find element index in vector in C++.

    Use Custom Function to Find Element Index in Vector in C++

    We can use a custom linear search function to find the given element’s position in the vector. Note that this is a pretty inefficient method to solve this problem. In the following example code, we declare a vector of integers and look for an arbitrary element position, which we output if the call is successful.

    #include <iostream>
    #include <string>
    #include <vector>
    
    using std::cout;
    using std::cerr;
    using std::endl;
    using std::string;
    using std::vector;
    
    int findIndex(const vector<int> &arr, int item) {
    
        for (auto i = 0; i < arr.size(); ++i) {
            if (arr[i] == item)
                return i;
        }
    
        return -1;
    }
    
    int main(int argc, char *argv[]) {
        vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
    
        auto pos = findIndex(arr, 32);
        pos != -1 ?
        cout << "Found the element " << 32 << " at position " << pos << endl :
        cout << "Could not found the element " << 32 << " in vector" << endl;
    
        exit(EXIT_SUCCESS);
    }
    

    Output:

    Could not found the element 32 in vector
    

    Use std::find Algorithm to Find Element Index in Vector in C++

    Alternatively, we may use the std::find algorithm that’s part of the STL library. This function returns the iterator to the first element that satisfies the condition. On the other hand, if no element is found, the algorithm returns the last element of the range. Mind though, returned iterator should be decremented by begin iterator to calculate the position.

    #include <iostream>
    #include <string>
    #include <vector>
    
    using std::cout;
    using std::cerr;
    using std::endl;
    using std::string;
    using std::vector;
    
    int findIndex2(const vector<int> &arr, int item) {
        auto ret = std::find(arr.begin(), arr.end(), item);
    
        if (ret != arr.end())
            return ret - arr.begin();
        return -1;
    }
    
    int main(int argc, char *argv[]) {
        vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
    
        auto pos2 = findIndex2(arr, 10);
        pos2 != -1 ?
        cout << "Found the element " << 10 << " at position " << pos2 << endl :
        cout << "Could not found the element " << 10 << " in vector" << endl;
    
        exit(EXIT_SUCCESS);
    }
    

    Output:

    Found the element 10 at position 9
    

    Use std::find_if Algorithm to Find Element Index in Vector in C++

    Another method to find the index of the element is to invoke the std::find_if algorithm. It’s similar to the std::find except that the third argument can be a predicate expression to evaluate each iterated element. If the expression returns true, then the algorithm will return. Notice that we pass the lambda expression as the third argument, which checks if the element is equal to 10.

    #include <iostream>
    #include <string>
    #include <vector>
    
    using std::cout;
    using std::cerr;
    using std::endl;
    using std::string;
    using std::vector;
    
    int main(int argc, char *argv[]) {
        vector<int> arr = {1,2,3,4,5,6,7,8,9,10};
    
        auto ret = std::find_if(arr.begin(), arr.end(),
                                [](int x) { return x == 10; });
    
        if (ret != arr.end())
            cout << "Found the element " << 10 << " at position "
                 << ret - arr.begin() << endl;
    
        exit(EXIT_SUCCESS);
    }
    

    Output:

    Found the element 10 at position 9
    

    Понравилась статья? Поделить с друзьями:
  • Как найти решение на тест
  • Как составить правила пожарной безопасности
  • Как найти потребность в основных средствах
  • Карта саратова как найти улицу
  • Объем цилиндра как найти примеры