簡體   English   中英

如何實現對向量的元素順序添加,在插入之前對其進行排序?

[英]How to realize sequent addition of elements to vector, sorting them before to insert?

我嘗試編寫將元素插入向量的程序,並按字母順序對它們進行排序。 之前要插入的元素與另一個元素進行比較,直到它超過已插入的元素。 在假定使用.insert()添加比較元素之后。 我想在不使用排序算法的情況下實現它。

std::string name;
std::vector<std::string> students;
std::vector<std::string>::iterator beg = students.begin();
  while (std::cin>>name){
        for (std::vector<std::string>::iterator e = students.end() ; beg !=e ; ) {
            if (!name.compare(*beg))
            {
                students.insert(beg, name);
                break;
            }
            else
                beg++;      
         }
    }

為了避免指向最后一個元素的迭代器失效,我每次迭代都會更新它。 問題是在這部分代碼之后我檢查了向量,但它是空的。

這個比較

if (!name.compare(*beg))

沒有意義。 它只檢查兩個字符串是否相等。

例如考慮以下代碼片段

std::string s1 = "one";
std::string s2 = "one";
std::cout << !s1.compare( s2 ) << '\n';

它的 output 是1 這意味着兩個對象相等。

此外,for 循環可以在沒有找到 position 的情況下結束,例如當最初向量為空時,可以在其中插入字符串。

而這個說法

std::vector<std::string>::iterator beg = students.begin();

必須在外部 while 循環內。 即迭代器應在循環的每次迭代中重新初始化。

這是一個演示程序,展示了如何實現內部循環。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

void insert( std::vector<std::string> &v, const std::string &s )
{
    auto it = std::begin( v );

    while (  it != std::end( v ) && not( s < *it ) ) ++it;

    v.insert( it, s );
}

int main() 
{
    std::string names[] = { "One", "Two", "Three" };
    std::vector<std::string> v;

    for ( const auto &s : names )
    {
        insert( v, s );
    }


    for ( const auto &s : v ) std::cout << s << ' ';
    std::cout << '\n';

    return 0;
}

程序 output 是

One Three Two

也就是說,字符串是按升序插入的。

相對於您的代碼片段,循環看起來像

while ( std::cin >> name )
{
    auto it = std::begin( students ); // or students.begin()

    while (  it != std::end( students ) && not( name < *it ) ) ++it;

    students.insert( it, name );
}

您也可以使用標准算法std::find_if來代替內部 while 循環。 例如

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

//...

while ( std::cin >> name )
{
    using namespace std::placeholders;
    auto it = std::find_if( std::begin( students ), std::end( students ), 
                            std::bind( std::greater_equal<>(), _1, name ) );

    students.insert( it, name );
}

對於空向量beginend是相同的,因此你永遠不會插入任何東西。

目前尚不清楚您為什么不想使用排序算法,因此我會提出以下建議:

std::string name;
std::vector<std::string> students;
while (std::cin>>name){
    students.push_back(name);
}
std::sort(students.begin(),students.end());

或者,用您最喜歡的排序程序替換最后一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM