Home > Mobile >  Select all elements but one with given index from std::vector?
Select all elements but one with given index from std::vector?

Time:06-26

Given a std::vector, for example of ints

std::vector vec{10, 20, 30}

how to select all items except of with given index, for example int i=1 resulting

std::vector {10, 30}?

CodePudding user response:

If you just want to "select" values from the original vector, I would create another vector with all the new values.

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> vect{ 10, 20, 30 };

    vector<int> selected;

    int i = 1;

    for (int j = 0; j < vect.size(); j  ) {
        if (j != i) {
            selected.push_back(vect[j]);
        }
    }

    // Added so you can check the new values
    for (int z = 0; z < selected.size(); z  ) {
        cout << selected[z] << " ";
    }

    return 0;
}

However, if you want to erase values from your original vector I would recommend using the vector.erase method (research the documentation).

CodePudding user response:

Here is a function for it where you can pass the vector and index and it will return you the new vector without that index element.

#include <iostream>
#include <vector>
using namespace std;


// returns a new vector without the v[index]

 vector<int> getElementsExceptIndex(vector<int> v, int index){
    vector<int> newVector;
    for(auto &x:v ){
     if(( &x - &v[0]) != index)
      newVector.push_back(x);
   }
    return newVector;
}

int main() {
   vector<int> originalVector{ 10, 20, 30 ,33,53};
   int index=1;
   
   auto RemovedIndexVector = getElementsExceptIndex(originalVector,index);
   
   for(auto item:RemovedIndexVector)
     cout<<item<<" ";
    return 0;
}
// Output - 10 30 33 53

Hope this helps

  • Related