将字符串存储在矢量中并对其进行排序

时间:2015-04-29 09:45:07

标签: c++ sorting vector

我想创建一个类,它将控制台中的字符串存储在向量中,然后使用选择排序按字母顺序对它们进行排序。 到目前为止,这是我的代码。

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

using namespace std;

class Dictionary
{
public:
    Dictionary();
    void read(vector<int>&words);
   void SelectionSort(vector <int> &num);
private:
    //vector<string> line_vector;
    string word;
    //vector<string> words;

};

Dictionary:: Dictionary()
{
    //line_vector = "<empty>";
    string word = "<empty>";
}

void Dictionary:: read(vector<int>& words)
{
    //vector<string> words;
    string word;
    while( cin >> word ) words.push_back(word);
}


////////////////////////////////////////////////////////////////////////////////////
void Dictionary:: SelectionSort(vector <int> &num)
{
      int i, j, first, temp;
      int numLength = num.size( );
      for (i= numLength - 1; i > 0; i--)
     {
           first = 0;                 // initialize to subscript of first element
           for (j=1; j<=i; j++)   // locate smallest between positions 1 and i.
          {
                 if (num[j] < num[first])
                 first = j;
          }
         temp = num[first];   // Swap smallest found with element in position i.
         num[first] = num[i];
         num[i] = temp;
     }
     return;
}


void print(vector<Dictionary>& a)
{
    for (int i = 0; i < a.size(); i++)
        cout << a[i];
    cout << "\n";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
    Dictionary dict;
    vector<Dictionary> str;
    dict.read(str);
    dict.SelectionSort(str);
    dict.print(str);

    return 0;
}

这些是错误:

In member function 'void Dictionary::read(std::vector<int>&)':
31:46: error: no matching function for call to 'std::vector<int>::push_back(std::string&)'
31:46: note: candidates are:
In file included from /usr/include/c++/4.9/vector:64:0,
                 from 3:
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]
       push_back(const value_type& __x)
       ^
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note:   no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const value_type& {aka const int&}'
/usr/include/c++/4.9/bits/stl_vector.h:931:7: note: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]
       push_back(value_type&& __x)
       ^

0 个答案:

没有答案