已知一个vector库,如何判断一个新的元素与已知库中的任意一个元素都不相同?
用STL中的std::find()
函数,或者你自己写个循环一个一个元素比较
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> words;
std::vector<int> count;
std::string word;
while (std::cin >> word)
{
auto itr = std::find(words.begin(), words.end(), word);
if (itr == words.end())
{
words.push_back(word);
count.push_back(1);
}
else
{
count[std::distance(words.begin(), itr)]++;
}
}
for (std::size_t i = 0; i < words.size(); i++)
std::cout << words[i] << " " << count[i] << '\n';
return 0;
}