display the index number of a vector

0

I want to show the index number in which certain information is positioned in a vector. I made a for to calculate which is the person who has the least amount of children and how many are. Once I get the least amount of children, I want to say who is the least. That's why I want to show the value of p.

for(int p=1;p<=5;p++){
       if (vector_numeroDeHijos[p]<menorTotal) {
           menorTotal=vector_numeroDeHijos[p];
        }
}

That is, if I set p to a value, I get what is in that position of the vector. What I want here is to get the value of p (not what is there). How can I do?

    
asked by happyperson 18.08.2016 в 03:56
source

3 answers

0

create a variable, which copies the value of p when the case of if

is met
int pos;//icionador
for(int p=1;p<=5;p++){
       if (vector_numeroDeHijos[p]<menorTotal) {
           menorTotal=vector_numeroDeHijos[p];
           pos = p;
        }

although I must ask you. Why is p equal to 1 and not% 0 ?

    
answered by 19.08.2016 / 23:16
source
2

A common way is usually to get the iterator to the desired element and then calculate the distance between the beginning of the series and that iterator:

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> v{9, 4, 7, 2, 8, 3, 5}; // vector de enteros
    for(auto& i : v)
        std::cout << i << ' ';
    std::cout << '\n';

    auto i_min = std::min_element(std::begin(v), std::end(v));
    auto pos = std::distance(std::begin(v), i_min);
    std::cout << "el menor es: " << *i_min
              << "\nde indice == " << pos << '\n';
}

Exit:

9 4 7 2 8 3 5
el menor es: 2
de indice == 3
    
answered by 18.08.2016 в 04:16
2

Since the question has been flagged

answered by 18.08.2016 в 17:29