C++新手求助:不使用set_intersection/set_difference实现向量比较
嘿,作为C++新手能有这样的实践想法超棒!我来帮你实现这个需求,代码里会加详细注释,保证你能轻松跟上~
完整实现代码
#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; int main() { // 1. 定义预定义的vector,并提前排序(方便后续查找) vector<string> predefined_words = {"secret", "password", "confidential"}; sort(predefined_words.begin(), predefined_words.end()); // 2. 动态读取用户输入到另一个vector vector<string> input_words; string word; cout << "请输入字符串(输入空行结束):" << endl; // 循环读取输入,直到用户输入空行(按下回车) while (getline(cin, word) && !word.empty()) { input_words.push_back(word); } // 3. 对输入的vector也进行排序(和预定义vector保持一致的排序状态) sort(input_words.begin(), input_words.end()); // 4. 遍历输入的每个元素,检查是否在预定义列表中 cout << "\n输出结果:" << endl; for (const string& w : input_words) { // 使用find函数查找元素是否存在 auto it = find(predefined_words.begin(), predefined_words.end(), w); if (it != predefined_words.end()) { // 找到匹配项,输出bleep cout << "bleep" << endl; } else { // 没找到,输出原元素 cout << w << endl; } } return 0; }
关键部分解释
- 排序操作:对两个vector都排序是为了让后续查找更高效(当然如果用
find的话不排序也能行,但排序后可以用更高效的binary_search,新手先从find入手更直观)。如果想用更高效的查找,可以把find换成binary_search(predefined_words.begin(), predefined_words.end(), w),返回bool值,代码会更简洁。 - 输入处理:用
getline读取整行输入,避免空格分割的问题,用户输入空行就停止输入,比单纯用cin >> word更灵活。 - 范围for循环:
for (const string& w : input_words)是C++11及以后的语法,遍历容器非常方便,新手可以尽快熟悉这种写法。
测试示例
假设预定义vector是{"secret", "password", "confidential"},用户输入:
hello secret world password
输出结果会是:
hello bleep world bleep
内容的提问来源于stack exchange,提问作者JAA
相关产品推荐
相关产品推荐

