Finding an element position in vector.

Finding an element position in vector.

Please explain a bit more about your issue. :slight_smile:

Take a vector of integer and a key (that we find in vector )…Now we are traversing the vector until found the key value or last index(otherwise)…If we found key then print the position , otherwise print “-1”.

 <span style="color: rgb(127, 96, 0);">#include <bits/stdc++.h>  </span>
 <span style="color: rgb(7, 55, 99); font-weight: bold">using</span> <span style="color: rgb(7, 55, 99); font-weight: bold">namespace</span> std;  



 <span style="color: rgb(7, 55, 99); font-weight: bold">int</span> main()  

  {  

      vector<<span style="color: rgb(7, 55, 99); font-weight: bold">int</span>>str;  

      <span style="color: rgb(7, 55, 99); font-weight: bold">int</span> flag,temp key, ,len,num;



       flag=0;

       cin>>len;



       <span style="color: rgb(7, 55, 99); font-weight: bold">for</span>(<span style="color: rgb(7, 55, 99); font-weight: bold">int</span> i=1; i<=len; i++)  

       {

           cin>>key;

           v.push_back(key);

       }



       cin>>num;



       <span style="color: rgb(7, 55, 99); font-weight: bold">for</span>(<span style="color: rgb(7, 55, 99); font-weight: bold">int</span> i=1; i<=len; i++)  

       {  

         <span style="color: rgb(7, 55, 99); font-weight: bold">if</span>(str[i]==num)  

         {  

            flag++;  

            temp=i-1;

            <span style="color: rgb(7, 55, 99); font-weight: bold">break</span>;

         }  

       }



     <span style="color: rgb(7, 55, 99); font-weight: bold">if</span>(flag!=0)    cout<<temp<<endl;

     <span style="color: rgb(7, 55, 99); font-weight: bold">else</span>           cout<<<span style="color: rgb(204, 0, 0);">"-1"</span><<endl;   

     str.clear();   



     <span style="color: rgb(7, 55, 99); font-weight: bold">return</span> 0;  

  }</div></div>

How to find an element position in vector (C++ STL) ?

please elaborate the problem , its not clear …

Finding an element position in c++ stl vector.