相关知识

  1. C++中的排序方法都有哪些? 一般情况下用sort(),需要稳定排序时则用stable_sort()。部分排序可用partial_sort()或nth_element(),前者会将前k小的数按升序排在前k位,其余元素无序;后者会把第k小的数排到第k位,其余元素无序(但前小而后大)。

第一轮

最后一版(AC)

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

int main() {
    int n;
    // getline(cin, s)是专门用来读取字符串的。
    cin >> n;
    cin.ignore();


    vector<string> strs;
    for (int i = 0; i < n; i++) {
        string s;
        getline(cin, s);
        strs.push_back(s);
    }

    sort(strs.begin(), strs.end());

    for (int i = 0; i < n; i++) {
        cout << strs[i] << endl;
    }

}
// 64 位输出请用 printf("%lld")

第二轮

第一版(段错误,0/10)

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

int main() {
    int n;
    cin >> n;
    vector<string> s;
    for(int i = 0; i < n; i++){
        cin >> s[i];
    }

    stable_sort(s.begin(), s.end());

    for(int i = 0; i < n; i++){
        cin >> s[i];
    }

    return 0;

}
// 64 位输出请用 printf("%lld")

  1. 程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起。
  2. 发现了一个低级错误——最后一个循环应该是cout << s[i]而非cin >> s[i]

第二版(段错误,0/10)

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

int main() {
    int n;
    cin >> n;
    vector<string> s;
    for(int i = 0; i < n; i++){
        cin >> s[i];
    }

    stable_sort(s.begin(), s.end());

    for(int i = 0; i < n; i++){
        cout << s[i];
    }

    return 0;

}
// 64 位输出请用 printf("%lld")

  1. 程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起。
  2. 发现了一个低级错误——最后一个循环应该是cout << s[i] << endl而非cout << s[i],因为题中的输出要换行。

第三版(段错误,0/10)

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

int main() {
    int n;
    cin >> n;
    vector<string> s;
    for(int i = 0; i < n; i++){
        cin >> s[i];
    }

    stable_sort(s.begin(), s.end());

    for(int i = 0; i < n; i++){
        cout << s[i] << endl;
    }

    return 0;

}
// 64 位输出请用 printf("%lld")

  1. 程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起。
  2. 终于注意到vector<string> s这里有问题,没有规定s的大小,应写为vector<string> s(n)
  3. 如果已经规定了大小,之后想改大小,可以怎么写呢?可以用resize()