编写一个程序,在一个 vector 而不是一个 set 中保存不重复的单词。
时间: 2023-05-11 16:04:42 浏览: 83
好的,这个问题可以用以下代码实现:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<string> words;
string word;
while (cin >> word) {
if (find(words.begin(), words.end(), word) == words.end()) {
words.push_back(word);
}
}
for (const auto& w : words) {
cout << w << " ";
}
return 0;
}
```
这个程序会从标准输入中读取单词,并将不重复的单词保存在一个 vector 中。如果一个单词已经存在于 vector 中,就不会再次添加。最后,程序会输出所有不重复的单词。
相关问题
怎么判断一个数在不在vector中
我们可以使用 std::find() 算法来判断一个数是否在 vector 中。该算法会在指定 vector 中查找指定元素,如果找到了,就返回该元素的迭代器;如果没有找到,则返回指向 vector 结尾的迭代器。
以下是使用 std::find() 来判断一个数是否在 vector 中的示例代码:
```C++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = { 1, 2, 3, 4, 5 };
int num = 3;
auto it = std::find(v.begin(), v.end(), num);
if (it != v.end()) {
std::cout << num << " is in the vector." << std::endl;
}
else {
std::cout << num << " is not in the vector." << std::endl;
}
num = 6;
it = std::find(v.begin(), v.end(), num);
if (it != v.end()) {
std::cout << num << " is in the vector." << std::endl;
}
else {
std::cout << num << " is not in the vector." << std::endl;
}
return 0;
}
```
输出结果为:
```
3 is in the vector.
6 is not in the vector.
```
在上面的示例代码中,我们首先定义了一个 int 类型的 vector,并初始化了一些数据。然后,我们使用 std::find() 算法来判断数字 3 和 6 是否在 vector 中,并根据结果输出相应的信息。
用c++编写一个在vector容器中判断某个数是否存在的代码
以下是用 C++ 编写一个在 vector 容器中判断某个数是否存在的代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
int target = 3;
if (find(nums.begin(), nums.end(), target) != nums.end()) {
cout << "Target exists in the vector." << endl;
} else {
cout << "Target does not exist in the vector." << endl;
}
return 0;
}
```
这段代码中,我们首先定义了一个 vector 容器 nums,其中包含了一些整数。然后我们定义了一个目标数 target,我们需要判断这个数是否存在于 nums 中。
我们使用了 C++ 标准库中的 find 函数来查找 target 是否存在于 nums 中。如果 find 函数返回的迭代器不等于 nums.end(),则说明 target 存在于 nums 中,否则说明 target 不存在于 nums 中。
注意:这段代码只是一个示例,实际使用时需要根据具体情况进行修改。