C++的好處是能夠從C++標準模板庫混合普通老式 - 數據指針和libc函數和算法:(注:使用了一些C++ 11功能)
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <ctype.h>
using namespace std;
size_t norepeat(const char* word) {
vector<char> digits;
vector<char>::iterator uniq;
// Filter the digits
copy_if(word, word+strlen(word), back_inserter(digits), ::isdigit);
// get the unique ones
sort(digits.begin(), digits.end());
uniq = unique(digits.begin(), digits.end());
// return amount
size_t uniques = std::distance(digits.begin(), uniq);
size_t duplicates = std::distance(uniq, digits.end());
return uniques - duplicates;
}
int main(void) {
cout << norepeat("hello 123 world 124") << endl;
cout << norepeat("hello world") << endl;
return 0;
}
輸出:
2
0
EDIT
只是爲了笑:寫了一個計數輸出迭代器類;它會將複製到其中的值的發生次數計入value
- >unsigned int
的地圖中。與count_if
算法(C++ lambda表達式)的norepeat
函數本身只有三個語句組合:一個變量聲明,過濾數字並返回計數的結果:自從我上次回答的基礎上的誤讀
#include <map>
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <ctype.h>
using namespace std;
template <typename T>
struct counter : public iterator<output_iterator_tag, T> {
typedef map<T, unsigned int> counter_type;
counter(counter_type* ptr) : mapptr(ptr) {}
// decorate with dereference and assignment
counter<T>& operator=(const T& t) {
mapptr->operator[](t)++;
return *this;
}
counter<T>& operator++() { return *this; }
counter<T>& operator*() { return *this; }
counter_type* mapptr;
};
size_t norepeat(const char* word) {
typename counter<char>::counter_type countert;
// Filter the digits
copy_if(word, word+strlen(word), counter<char>(&countert), ::isdigit);
// Count the ones that have a value of one
return count_if(countert.begin(), countert.end(),
[](const counter<char>::counter_type::value_type& kv) {
return kv.second==1; });
}
int main(void) {
cout << norepeat("hello 123 world 124") << endl;
cout << norepeat("hello world") << endl;
return 0;
}
如果我理解正確,您只需要在字符串中只出現一次的數字?那麼你的'std :: unique'應該可以工作。但在while循環之後執行。 – haavee
@haavee完全如您所說。我已經將它移到循環之外,但它仍然不起作用 – Gregy
因爲我錯了:-)'std :: unique'不是你想要的。 – haavee