简体   繁体   中英

Is there a way to take input from user in vector in C++?

I want to get my iterator to the last occurrence of 1.


For example, in a vector A[0, 0, 1, 0, 1, 0, 1, 0, 0] I want to get my iterator to 6th place in 0 based indexing. I want to do this using vector function but the array won't be hard-coded in the program. The program is to take a vector from user consisting of 0s and 1s and and then get the iterator to last occurrence of 1, thanks!

logically speaking I want to do something like this to get input from user:

std::vector<int> b, c;
        for (auto d : b)
            std::cin >> c;
            b.push_back(c);

You can use std::upper_bound() to find the index but the array need to be sorted.

Or, you can convert the array to string then use std::string::find() to find the element.

To read in numbers until there is something that isn't a number, you need to loop testing the result of >>

std::vector<int> a;
for (int b; std::cin >> b;) { a.push_back(b); }

Then you can std::find from the end by using std::reverse_iterator s

auto it = std::find(a.rbegin(), a.rend()).base();
// showing the index
std::cout << std::distance(a.begin(), it);

I would suggest you to make a vector funtion with parameter of another vector.

like,

vector<int>Printvectors(vector<int>vectornew){} // If you want the return type to be 
                                                //            a vector

And to accept the value of the users into the vectors what u can do is-

vector<int>a;

while(cin>>i){
a.push_back(i);
}

a.sort(a.begin(),a.end()); // to sort
vector<int>Printvectors(vector<int>a);

and use the lower bound function i would recommend for the vector to get the iterator at the desired place.use std::string::find() to find the element..

i suggest you to use something like this:

for(int i=0;i<array.length;i++){
   array[i]=cin<<"use user input here"
 }

for code mistake please apologize me but i no long use c++ since 4 years

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM