user2670499
user2670499

Reputation: 31

Remove duplicate string in an array

i'm new to c++ and i'm looking for a way to remove duplicate strings from an array of strings that looks like this: string exempleArray[]= {"string1", "string2", "string1"}; after the code it should look like this: "string1", "string2", but the order doesn't matter at all. Thanks a lot for your time.

Upvotes: 3

Views: 4724

Answers (2)

juanchopanza
juanchopanza

Reputation: 227418

If the order doesn't matter, you can first sort the array with std::sort, then use std::unique to remove the duplicates.

std::sort(std::begin(exampleArray), std::end(exampleArray));
auto it = std::unique(std::begin(exampleArray), std::end(exampleArray));

Here, it points to one past the end of the new, unique range. Note that since you started with a fixed size array, you cannot reduce its size to the number of unique elements. You would need to copy the elements to a container whose size can be determined at runtime. std::vector<std:string> is an obvious candidate.

std::vector<std::string> unique_strings(std::begin(exampleArray), it);

Note if you started with an std::vector<std::string> instead of a fixed size array, you would be able to avoid the copy and remove elements from the original vector:

std::vector<std::string> strings = {"string1" "string2" "string1"};
std::sort(strings);
auto it = std::unique(std::begin(strings), std::end(strings));
strings.erase(it, strings.end());

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

If you want this, then prefer storing them in a std::set instead. It will automatically store unique items.

Or if you have array (or std::vector) already and cannot use std::set for some reason, then make use of std::sort followed by std::unique to achieve that.

Upvotes: 3

Related Questions