당신이 한 번 이상 목록을 통과해야하고, 당신이 모르는 경우 또는 위치를 중복 발생하는 것이기 때문에 숫자가 있으면 (있는 경우),이를 해결하는 한 가지 방법은 먼저 "통계"를 수집 한 다음 수집 한 것에서 첫 번째 비 중복을 결정할 수 있습니다.
이
#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
제목에 "vector"또는 임의의'벡터 '또는 '벡터 '등의 내용을 사용 하시겠습니까? 아니면 다른 것이 있습니까? 귀하의 질문에서 분명히 명확하지 않습니다. –
Useless
불행히도, 아닙니다! 나는 요소의 순서를 어지럽히 지 못한다. 그대로 있어야한다. – Xigma