0

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.

Community
  • 1
  • 1
user2083364
  • 744
  • 1
  • 7
  • 20
  • 1
    just use std::unique? – billz Oct 28 '13 at 08:53
  • C++ have many nice [algorithms](http://en.cppreference.com/w/cpp/algorithm) in the standard library, for example [`std::unique`](http://en.cppreference.com/w/cpp/algorithm/unique) (or [`std::unique_copy`](http://en.cppreference.com/w/cpp/algorithm/unique_copy) if you don't want to modify the original collection). – Some programmer dude Oct 28 '13 at 08:57
  • IMO (unique + erase) combination should be applied. – Abhishek Bansal Oct 28 '13 at 09:02

1 Answers1

1

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"

asalic
  • 949
  • 4
  • 10
  • No need for the custom comparator, the two-argument version of `std::unique` uses `operator==` by default. – Some programmer dude Oct 28 '13 at 08:59
  • @JoachimPileborg Yes I know, but I like to give the more complete version, maybe it will help the OP or others, they can change to whatever type of object they want (considering that that object doesn't have the **==** op) – asalic Oct 28 '13 at 09:01
  • IMO it is better to add an erase operation after it because the container size is not modified in this action. – Abhishek Bansal Oct 28 '13 at 09:02
  • @AbhishekBansal You're right, I tried to be the fastest and I forgot that part... – asalic Oct 28 '13 at 09:08
  • std::erase doesn't exist, erase is a member of std::vector object. – user2083364 Oct 28 '13 at 09:30
  • another error is: Assigning to 'int' from incompatible type 'std::basic_string' for string `std::vector myvector (mys,mys+6);` – user2083364 Oct 28 '13 at 09:34