C++ 根据字符串输入在句子中的位置对其排序的更快方法是什么?

C++ 根据字符串输入在句子中的位置对其排序的更快方法是什么?,c++,optimization,C++,Optimization,在参加全国信息学奥林匹克竞赛时,遇到了如下问题: 用户输入句子中的单词数量(n),然后继续输入单词及其位置(用空格分隔)。 要求您按照正确的词序输入句子 例如: 输入: 4 this 1 sentence 4 is 2 a 3 输出: this is a sentence 限制: 1 <= N <= 3 * 10^5 1 <= Size of a word <= 50 1std::无序地图对于这个问题来说有点过分。由于提供了元素的顺序,您可以使用std::vecto

在参加全国信息学奥林匹克竞赛时,遇到了如下问题: 用户输入句子中的单词数量(n),然后继续输入单词及其位置(用空格分隔)。 要求您按照正确的词序输入句子

例如:

输入:

4
this 1
sentence 4
is 2
a 3
输出:

this is a sentence
限制:

1 <= N <= 3 * 10^5
1 <= Size of a word <= 50

1
std::无序地图对于这个问题来说有点过分。由于提供了元素的顺序,您可以使用
std::vector
,只需将元素放入输入告诉您的向量中即可。这将程序代码简化为

int main()
{
    int records;
    std::cin >> records;
    std::vector<std::string> sentence(records);
    std::string word;
    int place;
    while (std::cin >> word >> place)
        sentence[place - 1] = std::move(word); // subtract one as input is 1 based index, use move to save an allocation and copy
    for (auto const& e : sentence)
        std::cout << e << " ";
}
intmain()
{
int记录;
std::cin>>记录;
向量句(记录);
字符串字;
国际广场;
while(std::cin>>word>>place)
句子[place-1]=std::move(word);//减去一,因为输入是基于1的索引,使用move保存分配并复制
for(自动const&e:句子)

std::你在计时时也可以测量输出吗?为什么不简单地使用一个向量呢?单词减去1后的索引就是向量中的索引。你从第一次输入中知道的向量的大小。
std::vector v…v.[index-1]=s;
甚至
句子[place-1]=std::move(word)它将时间降低到0.528,但仍然不是第一个点的0.12。关于它们是如何完成的,有任何想法吗?@ Rekle CUT和CIN是慢的。@ ZDF是使用C++的12个解决方案。如果它们回到C,使用<代码> PRINTF 和C字符串,那么它们可能会更快,因为流是慢的。也许它们是迷你的。最大化内存分配。
int main()
{
    int records;
    std::cin >> records;
    std::vector<std::string> sentence(records);
    std::string word;
    int place;
    while (std::cin >> word >> place)
        sentence[place - 1] = std::move(word); // subtract one as input is 1 based index, use move to save an allocation and copy
    for (auto const& e : sentence)
        std::cout << e << " ";
}