vector 动态添加


#include <iostream> #include <vector> #include <string> #include <algorithm> int main() { std::vector<std::string> myVector; // 创建一个空的vector<string> std::string input; std::cout << "请输入字符串(输入exit退出):" << std::endl; while (true) { std::cin >> input; if (input == "exit") { break; // 如果输入为exit,则退出循环 } // 查找输入的字符串是否已经存在于vector中 auto it = std::find(myVector.begin(), myVector.end(), input); if (it == myVector.end()) { myVector.push_back(input); // 如果字符串不存在,则添加到vector中 } else { std::cout << "该字符串已存在!" << std::endl; } } std::cout << "你输入的字符串为:" << std::endl; for (const auto& str : myVector) { std::cout << str << std::endl; // 输出vector中的所有字符串 } return 0; }

如果vector包含结构体,而结构体中有一个string类型的成员,要判断结构体中的成员string是否存在,如果不存在则动态添加,可以使用std::find_if()函数结合lambda表达式来查找元素是否存在,如果返回的迭代器指向vectorend()位置,则表示元素不存在,可以使用push_back()函数来添加元素。

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

struct MyStruct {
    std::string name;
    int age;
};

int main() {
    std::vector<MyStruct> myVector; // 创建一个空的vector<MyStruct>

    std::string input;
    std::cout << "请输入姓名(输入exit退出):" << std::endl;

    while (true) {
        std::cin >> input;
        if (input == "exit") {
            break; // 如果输入为exit,则退出循环
        }
        
        // 查找姓名是否已经存在于vector中的结构体中
        auto it = std::find_if(myVector.begin(), myVector.end(), [&](const MyStruct& s) {
            return s.name == input;
        });
        
        if (it == myVector.end()) {
            // 如果姓名不存在,则添加到vector中的结构体中
            MyStruct newStruct;
            newStruct.name = input;
            myVector.push_back(newStruct);
        } else { 
        // 如果姓名存在,则修改对应的年龄
std::cin >> it->age;
} } std::cout << "你输入的姓名为:" << std::endl; for (const auto& s : myVector) { std::cout << s.name << std::endl; // 输出vector中的所有姓名 } return 0; }

 

posted @ 2023-08-29 10:39  SusieSnail_SUN  阅读(8)  评论(0编辑  收藏  举报