### Container not expensive

Hello everyone;
I have a small question. I have an array like this :A=[7 8 5 9 10 5 11 12 5 10 11 12] . I need to find the index of 5 values in A and get the latest one; which means the index of 5 are B=[2 5 8] and change the latest one which is 8 to 100. I stacked the index values by using push_back()and generated B vector but it is so costly. How can I achieve this task more efficiently ? Thank you so much
Search backwards from the end and change the first one you come to.
Thank you @lastchance. I guess I did not understand well. You mean, without creating vector B, when I finish to read the indexes of A until the end of the vector, will I do a search backward?
Possibly:

 1234567891011121314151617181920212223 #include #include #include #include int main() { const std::vector A {7, 8, 5, 9, 10, 5, 11, 12, 5, 10, 11, 12}; const int to_find {5}; std::vector B; B.reserve(A.size()); for (size_t i = 0; i < A.size(); ++i) if (A[i] == to_find) B.emplace_back(i); B.back() = 100; std::copy(B.begin(), B.end(), std::ostream_iterator(std::cout, " ")); std::cout << '\n'; }

 2 5 100

Last edited on
@learner999, I may or may not have misunderstood what you wanted. A doesn't have anything with index 100, so why would you want to create a separate vector B containing two indices and a non-entity?

To avoid an XY problem, please make your ultimate intention clearer (give the WHOLE assignment).

 12345678910111213141516171819202122232425262728293031323334 #include #include #include using namespace std; // Just for output template ostream & operator << ( ostream &out, const vector &V ) { for ( T e : V ) out << e << " "; return out; } int main() { vector A = { 7, 8, 5, 9, 10, 5, 11, 12, 5, 10, 11, 12 }; cout << A << '\n'; int target = 5; int changeTo = 100; auto it = find( A.rbegin(), A.rend(), target ); // search BACKWARDS if ( it == A.rend() ) { cout << "Not found\n"; } else { *it = changeTo; cout << A << '\n'; } }

 7 8 5 9 10 5 11 12 5 10 11 12 7 8 5 9 10 5 11 12 100 10 11 12

Last edited on
@lastchance - I think he wants a new vector containing the indexes from A corresponding to the required number - with the last index changed to 100.
Thank you so much @lastchance and @seeplus. I totally understood what you did and you got what I want to do. It will be better for me the version without generating another vector B.
Thank you so much for both of the answers..
Last edited on
 the version without generating another vector B.

Eh??? I don't understand. Can you explain again in more detail exactly what is your data and you are trying to accomplish. Provide a simple example of your input and expected output - noting that in the OP the syntax used is not that of c/c++.
Topic archived. No new replies allowed.