版本比较
C++ vector详解
正文
增加 6 行删除 6 行
71 行未改动72737475767677787980151 行未改动全部展开23223323423523623623723823924024124224224324424524624624724824925025125125225325425525625725725825926026130 行未改动71 行未改动// 使用下标运算符(不进行边界检查)int a = vec[0]; // 越界时行为未定义
// 使用 at() 方法(进行边界检查,越界抛出 std::out_of_range)int b = vec.at(1); int b = vec.at(1);
// 返回第一个元素int front = vec.front();
151 行未改动全部展开
struct Person { std::string name; int age;
Person(const std::string& n, int a) : name(n), age(a) {}};
int main() { std::vector<Person> people;
// 使用 emplace_back 直接在容器内构造对象 people.emplace_back("Alice", 30); people.emplace_back("Bob", 25);
// 遍历 for (const auto& p : people) { std::cout << p.name << " " << p.age << std::endl; }
// 按年龄排序 std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) { return a.age < b.age; });
return 0;}```
30 行未改动