• C++
  • vector入门到放弃3

  • @ 2025-2-16 16:36:49

🌟 场景1:输入学生成绩(数量未知)

需求:老师想输入全班成绩,但不确定有多少学生,输入-1时停止。

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> scores;
    int score;
    
    cout << "请输入成绩(输入-1结束):" << endl;
    while(true) {
        cin >> score;
        if(score == -1) break;
        scores.push_back(score); // 动态添加到魔法书包
    }
    
    cout << "共录入" << scores.size() << "个成绩:" << endl;
    for(int s : scores) {
        cout << s << " ";
    }
    return 0;
}

🍭 场景2:逐行输入单词

需求:用户输入多行文本,每行多个单词,存储到二维vector中。

#include <iostream>
#include <vector>
#include <sstream> // 用于分割字符串
using namespace std;

int main() {
    vector<vector<string>> textLines;
    string line;
    
    cout << "请输入文本(空行结束):" << endl;
    while(getline(cin, line) && !line.empty()) {
        vector<string> words;
        stringstream ss(line);
        string word;
        while(ss >> word) {
            words.push_back(word); // 把每行的单词存入小书包
        }
        textLines.push_back(words); // 把小书包加入大书包
    }
    
    // 打印结果
    for(auto& line : textLines) {
        for(auto& word : line) {
            cout << "[" << word << "] ";
        }
        cout << endl;
    }
    return 0;
}

🎮 场景3:游戏地图动态输入

需求:用户逐行输入迷宫地图的行,#代表墙,.代表路。

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<vector<char>> maze;
    string row;
    
    cout << "请输入迷宫地图(每行相同长度,空行结束):" << endl;
    while(getline(cin, row) && !row.empty()) {
        vector<char> currentRow;
        for(char c : row) {
            currentRow.push_back(c);
        }
        maze.push_back(currentRow);
    }
    
    // 打印迷宫验证
    cout << "您输入的迷宫:" << endl;
    for(auto& r : maze) {
        for(char c : r) {
            cout << c;
        }
        cout << endl;
    }
    return 0;
}

📁 场景4:从文件读取数据

假设有一个scores.txt文件

95 88 72
60 85 90
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

int main() {
    vector<vector<int>> allScores;
    ifstream file("scores.txt");
    
    string line;
    while(getline(file, line)) {
        vector<int> scores;
        stringstream ss(line);
        int num;
        while(ss >> num) {
            scores.push_back(num);
        }
        allScores.push_back(scores);
    }
    
    // 打印结果
    for(auto& s : allScores) {
        for(int n : s) {
            cout << n << " ";
        }
        cout << endl;
    }
    return 0;
}

💡 关键技巧总结

  1. 动态扩展:不需要预先知道数据量,用push_back()随时添加
  2. 灵活结构:一维、二维甚至多维数据都能轻松处理
  3. 输入终止:通过特定值(如-1)、空行或文件EOF结束输入
  4. 组合应用:常与stringstream结合处理字符串分割

🎨 互动挑战

尝试写一个程序:让用户输入多个商品信息(名称、价格),存储到vector中,然后按价格排序~ 🛒 需要用到结构体哦!
提示:

struct Product {
    string name;
    double price;
};
vector<Product> products;

0 条评论

目前还没有评论...