Hello, World!

日頃のメモ

c++で文字列をsortとunique

複数の文字列を重複を削除して、アルファベット順に並べるプログラム

#include <iostream>
#include <list>
#include <string>
using namespace std;

void print (list<string> &list1) {
  for (auto x: list1) {
    cout << x << " ";
  }
  cout << endl;
}

void print (list<int> &list2) {
  for (auto x: list2) {
    cout << x << " ";
  }
  cout << endl;
}

int main(int argc, char const* argv[])
{

  list<string> list1 = { "ACC","CCW","CWA","ACC","WAC","CCT","CTT","TTT" };
  list<int> list2 = {1,1,1,1,1,2,3,1,2,3,2,8,9};

  cout << "入力された文字" << endl;
  print(list1);
  print(list2);

  list1.unique();
  cout << "After unique list1: ";
  print(list1);

  list2.unique();
  cout << "After unique list2: ";
  print(list2);
  cout << endl;

  list1.sort();
  list1.unique();
  cout << "After sort&unique list1: ";
  print(list1);

  list2.sort();
  list2.unique();
  cout << "After sort&unique list2: ";
  print(list2);

  return 0;
}

実行結果

$ g++ -std=c++11 test.cpp
$ ./a.out
入力された文字
ACC CCW CWA ACC WAC CCT CTT TTT
1 1 1 1 1 2 3 1 2 3 2 8 9
After unique list1: ACC CCW CWA ACC WAC CCT CTT TTT
After unique list2: 1 2 3 1 2 3 2 8 9

After sort&unique list1: ACC CCT CCW CTT CWA TTT WAC
After sort&unique list2: 1 2 3 8 9

list1で"ACC","CCW","CWA","ACC","WAC","CCT","CTT","TTT"の並びだとunipueされないが、"ACC","ACC","CCW","CWA","WAC","CCT","CTT","TTT"の場合ACC二つが隣り合ってるので片方は削除される


参考サイト
http://kaworu.jpn.org/cpp/std::list::unique
http://kaworu.jpn.org/cpp/auto#Range_based_for_.2B_auto_.E5.9E.8B.E3.81.AE.E4.BE.8B
https://qiita.com/ysk24ok/items/30ae72f4f1060b088588

あとついでに
https://dixq.net/forum/viewtopic.php?f=3&t=5601
https://qiita.com/hal1437/items/b6deb22a88c76eeaf90c