scanf函数和cin的区别、类的数组、C++排序函数

给定n个字符串,将这n个字符串按照字典序进行排列,此处用排列函数是C++的库函数sort,产生如下两个疑问,望大佬解答

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

using namespace std;
/*
**********************************************
Q1:为什么定义类的数组,无法用sort函数排序呢?
会出现数组越界的情况,求解答
*********************************************
int main()
{
    string str[1000];
    int n;
    scanf("%d",&n);
    for(int i = 0;i < n;i++){
        scanf("%s",str+i);
        str[i] = str[i] +'';
    }
    sort(str,str+n-1);
    for(int i =0;i < n;i++)
        printf("%s
",str+i);
    return 0;
}
**********************************************
*/
/*
以下代码正常运行
*/
int main()
{
    vector<string> str;
    string newstr;
    int n;
    scanf("%d",&n);
    for(int i = 0;i < n;i++){
        cin>>newstr;
        //scanf("%s",newstr);  //Q2:这里用scanf进行读取输入,为什么会出错呢?
        str.push_back(newstr);
    }
    sort(str.begin(),str.end());
    for(int i =0;i < n;i++)
        cout<<str[i]<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/qiang-wei/p/9363469.html