Question

There are a lot of questions how to remove simply repeating strings:

link

but my question differs from them.

For example, if I have entry vector<string>:

{"111", "222", "222", "222", "333", "222"}

I need to get the following result:

{"111", "222", "333", "222"}

it means deleting nearby repeating values only.

My current temporary solution is to create another vector, copy each element from entry vector with checking if this element isn't equal to the last element of the second vector.

Was it helpful?

Solution

Here is an example adapted from the std::unique page:

bool comp (std::string &i, std::string &j) {
  return (i==j);
}

int main () {
  std::string mys[] = {"111", "222", "222", "222", "333", "222"};       
  std::vector<std::string> myvector (mys,mys+6);
  myvector.erase(std::unique (myvector.begin(), myvector.end(), comp), myvector.end());  
  return 0;
}

and the link to the original code:

http://www.cplusplus.com/reference/algorithm/unique/

UPDATE

As suggested in comments, you can skip the comparator method, but keep in mind that you can use it if the objects in the vector don't have the == . I just put this example because it is 100% complete and it can be easily extended to other types of objects.

UPDATE 2

Yes, and you should erase the last part of the vector, because, as the doc says, the unique method will return "an iterator to the element that should be considered its new past-the-end element"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top