あなたは少なくとも一度リストを通過する必要があり、あなたが知っていない場合、またはどこで重複が発生しますので、 (ある場合)、これを解決する1つの方法は、最初に "統計"を収集し、次に収集したものから最初の非重複を判断することです。
が
#include <algorithm>
#include <unordered_map>
#include <iostream>
#include <vector>
#include <string>
// struct to hold some information on the numbers
struct info
{
std::string number;
int count;
int position;
info(const std::string n, int c, int p) : number(n), count(c), position(p) {}
};
int main()
{
std::vector<std::string> data = {"12","12","12","12","13","14","15", "15", "15", "15", "18"};
std::unordered_map<std::string, info> infoMap;
std::vector<info> vInfo;
int pos = 0;
// loop for each data element
std::for_each(data.begin(), data.end(), [&](const std::string& n)
{
// insert entry into the map
auto pr = infoMap.insert(std::make_pair(n, info(n, 0, pos)));
// bump up the count for this entry.
++pr.first->second.count;
// bump up the postion number
++pos;
});
// create a vector of the information with a count of 1 item.
std::for_each(infoMap.begin(), infoMap.end(), [&](std::unordered_map<std::string, info>::value_type& vt) { if (vt.second.count == 1) vInfo.push_back(vt.second); });
// sort this by position
std::sort(vInfo.begin(), vInfo.end(), [&](const info& pr1, const info &pr2){return pr1.position < pr2.position; });
// output the results
if (vInfo.empty())
std::cout << "All values are duplicated\n";
else
std::cout << "The first number that isn't repeated is " << vInfo.front().number << "\n";
}
Live Example
まず、我々は単にベクトル内のすべてのエントリを通過し、ちょうど各項目のカウントを集計:
はここstd::unordered_map
を使った例です。さらに、アイテムが見つかった元のリストにその位置を格納します。
その後、カウント数が1のものを除外してベクトルにコピーします。次に、元のリストで見つかった位置に基づいてこのベクトルをソートします。
は常にソートされたデータですか? – PaulMcKenzie
あなたのタイトル、または任意の 'ベクトル'、または 'ベクトル 'のように'ベクトル 'を書いていますか?あなたの質問からはっきりと分かりません。 –
Useless
残念ながら、そうではありません!私は要素の順序を混乱させることはできません、それはそのままでなければなりません。 – Xigma