注册 登录
编程论坛 C++教室

暑假作业里有一道题一点头绪也没有,求帮忙

根根本根 发布于 2018-08-30 14:08, 1474 次点击
只有本站会员才能查看附件,请 登录
9 回复
#2
rjsp2018-08-30 14:44
程序代码:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;

int main( void )
{
    size_t n;
    string buf[20];

    // 输入
    cin >> n;
    copy_n( istream_iterator<string>(cin), n, buf );

    // 排序
    sort( buf, buf+n, [](const string& a, const string& b){return a+b>b+a;} );

    // 输出
    copy( buf, buf+n, ostream_iterator<string>(cout,"") ) = "\n";
}


#3
根根本根2018-08-30 14:47
copy_n和copy是什么呀我还没学过呢
而且sort的这种用法也没学过
#4
根根本根2018-08-30 14:50
只有本站会员才能查看附件,请 登录
#5
rjsp2018-08-30 14:51
回复 3楼 根根本根
那只好这样了:
程序代码:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;

bool cmp( const string& a, const string& b )
{
    return a+b > b+a;
}

int main( void )
{
    size_t n;
    string buf[20];

    // 输入
    cin >> n;
    for( size_t i=0; i!=n; ++i )
        cin >> buf[i];

    // 排序
    sort( buf, buf+n, &cmp );

    // 输出
    for( size_t i=0; i!=n; ++i )
        cout << buf[i];
    cout << endl;
}

#6
rjsp2018-08-30 14:56
回复 4楼 根根本根
从截图上看,IDE用的是古老的dev-cpp,编译器用的是古老的gcc4.8.1,编译参数也不加 -std=c++11
现在Windows上mingw已经是8.1.0版本了
#7
根根本根2018-08-30 15:09
#include <bits/stdc++.h>
using namespace std;
bool cmp(string a,string b ) {
    return a+b > b+a;
}
int main( void ) {
    int n;
    string buf[20];
    cin >> n;
    for( int i=0; i<n; i++ ) {
        cin >> buf[i];
    }
    sort( buf, buf+n, cmp );
    for( int i=0; i<n; i++ ) {
        cout << buf[i];
    }
    return 0;
}
这样也可以诶

那个size_t是不是就是int?
#8
rjsp2018-08-30 15:47
你是说将 bool cmp( const string& a, const string& b ) 改为 bool cmp(string a,string b ) 的事吗?
那你觉得这两者差别在哪里?

size_t当然不是int,否则C++标准和C标准为什么要增加这种类型呢?
size_t 是C/C++标准中唯一可标识 对象尺寸、数组索引、循环计数 的类型,而其它类型标准都不作保证。
比如操作符 sizeof 的表达式类型就是 size_t,比如函数 strlen 的返回类型就是 size_t,比如 vector::operator[] 的参数类型(也就是索引)就是 size_t。
#9
旦井2018-09-18 19:31
#10
Jonny02012018-09-18 20:19
回复 7楼 根根本根
你需要好好了解一下 C/C++ 为什么要存在 size_t 这种型别
1