-3

Been programming for 1 week. I have vector<tuple<string, string, T>> edgesVector. Which contains two strings and an INT. How do I delete a tuple within the vector that contains two specific strings?


remove_edge(const string& u, const string& v) {

    for (int i = 0; i<edgesVector.size(); i++ ) {
        if (get<0>(edgesVector[i]) == u && get<1>(edgesVector[i]) == v){
            edgesVector.erase(i);
        }
        if (get<1>(edgesVector[i]) == u && get<0>(edgesVector[i])== v){
            edgesVector.erase(i);
        }

    }           


}

2 Answers2

3

You use std::remove_if, and pass the result to edgesVector.erase. This is called the erase-remove idiom.

void remove_edge(const string& u, const string& v) {
    auto it = std::remove_if(edgesVector.begin(), edgesVector.end(), [&](auto & tup){ return (get<0>(tup) == u) && (get<1>(tup) == v); }); // removes elements that match u, v
    it = std::remove_if(edgesVector.begin(), it, [&](auto & tup){ return (get<0>(tup) == v) && (get<1>(tup) == u); }); // removes elements that match v, u
    edgesVector.erase(it, edgesVector.end()); // resize the vector to only hold live elements
}
Caleth
  • 52,200
  • 2
  • 44
  • 75
0

The erase-remove idiom commented by others is the way to go, but the problem with your snippet is easily solved.

std::vector::erase takes an iterator as a parameter whereas you're passing it an index.

for (auto itr = edgesVector.begin(); itr != edgesVector.end();) {
    if ((get<0>(*itr) == u && get<1>(*itr) == v) ||
        (get<1>(*itr) == u && get<0>(*itr)== v))
        itr = edgesVector.erase(itr);
    else
        ++itr;
    }
}
acraig5075
  • 10,588
  • 3
  • 31
  • 50
  • This only removes one element. OP may want to remove all the matching elements – Caleth Apr 26 '21 at 12:34
  • 1
    erase returns a new iterator, to the next element of the erased. So the algorithm can erase multiple elements, by some adjustments. Use `itr = edgesVector.erase(itr);`. To not skip elements, you need to increment itr only if the element is NOT erased – king_nak Apr 26 '21 at 14:30