0

I have a std::vector of std::pair of std::string where the language and translation are the values. These are the values in my vector of pair

 0. {English, Love},  
 1. {Spanish, Amor},  
 2. {Tagalog, Mahal},  
 3. {English, Love}

What I wanted to do is to only remove the index 3, but in my code if I try to remove the index 3, both index 0 and 3 are removed.

Here's my code:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include <utility>

auto main() -> int {

  using pair_of = std::vector<std::pair<std::string, std::string>>;
  using str_pair = std::pair<std::string, std::string>;

  pair_of language_translation{};

  language_translation.emplace_back(std::make_pair("English", "Love"));
  language_translation.emplace_back(std::make_pair("Spanish", "Amor"));
  language_translation.emplace_back(std::make_pair("Tagalog", "Mahal"));
  language_translation.emplace_back(std::make_pair("English", "Love"));

  std::string language{"English"};
  std::string translation{"Love"};

  auto selected_pair = std::remove_if(
    language_translation.begin(), language_translation.end(),
    [&](const str_pair &data_pair) {
      if(data_pair.first == language && data_pair.second == translation) {
        return true; 
      }
      else {
        return false;
      }
    }
  );
  
  language_translation.erase(selected_pair, language_translation.end());
  
  for(const auto &pair : language_translation) {
    std::cout << pair.first << ": " << pair.second << std::endl;
  }

}

The output result is

Tagalog: Mahal
Spanish: Amor

What other algorithm can I use to solve a problem like this? Can you guys give an example? Thank you!

Gil Rovero
  • 35
  • 5
  • What's wrong with remove_if? – Pepijn Kramer Oct 21 '22 at 08:45
  • I don't know if I use a nice algorithm `std::remove_if` but I can't find any solution to my problem – Gil Rovero Oct 21 '22 at 08:49
  • ot: `pair_of` is a little confusing for a vector of pairs of strings – 463035818_is_not_an_ai Oct 21 '22 at 08:52
  • 2
    So you want to remove only the *last* instance of a specific tuple? Or is this an attempt to fix a Y solution to an X problem (ex: the problem may be you want to remove duplicates, and this was the way you came up with doing it, but it didn't work out like you hoped and you're asking how to fix *that*, not the real problem: duplicate removal). – WhozCraig Oct 21 '22 at 08:56
  • ot: `emplace` should be called with the arguments for the constructor, passing an element defeats the purpose of `emplace`, you could use `push_back` as well – 463035818_is_not_an_ai Oct 21 '22 at 08:56

1 Answers1

6

To delete by index you can do something like this:

language_translation.erase(std::next(language_translation.begin(), index));
sklott
  • 2,634
  • 6
  • 17