Home > front end >  How to erase specific index of std::vector of std::pair?
How to erase specific index of std::vector of std::pair?

Time:10-21

I have a std::vector of std::pair of std::string where the language and translation are the values. These are 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>>;

  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 std::pair<std::string, std::string> &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!

CodePudding user response:

To delete by index you can do something like this:

language_translation.erase(std::next(language_translation.begin(), index));
  • Related