排序字符矢量

时间:2017-09-15 07:18:03

标签: c++ string vector char

我试图将插入的字符串转换为Cstring中的向量并对它们进行排序。我有一切工作,除非我创建字符串插入的最后一个字只是重复。我知道它在这个区域附近

while(getline((text), words, ' '))
    spliter.push_back(words.c_str());

我的代码搞砸了,所以我想知道是否有人可以告诉我哪里出错了并且可以解决它。我知道一个普通的C ++字符串会更有效率,但它必须以这种方式完成而我;有点丢失

{ const int limit  =301;

 char input[limit];
string words;

 characters

cin.getline(input, limit);


words =input;

vector <const char*> spliter;

stringstream text(words);

 while(getline((text), words, ' '))

        spliter.push_back(words.c_str());

        for(auto x:spliter) cout << x << " "; cout << endl ;

    auto cstr_compare = [](const char* s1, const char* s2) {

        return strcmp(s1,s2) < 0; };

    sort(spliter.begin(), spliter.end(), cstr_compare);

    for(auto x:spliter) cout << x << " "; cout << endl;

}

1 个答案:

答案 0 :(得分:0)

我可以建议你这个解决方案吗?

#include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <cstring>

using namespace std;

void ctokenize(const stringstream& text, vector<const char*>& tokens)
{
    std::string::size_type pos = 0;
    std::string::size_type lastPos = 0;

    string str = text.str();

    while(std::string::npos != pos) {
        // find separator
        pos = str.find(" ", lastPos);

        // Found a token, add it to the vector.
        string strFound = str.substr(lastPos, pos - lastPos);
        tokens.push_back(strdup(strFound.c_str()));

        // set lastpos
        lastPos = pos + 1;
    }
}

int main()
{
    const int limit = 301;
    char input[limit];
    string words;

    //characters

    cin.getline(input, limit);

    words = input;

    vector<const char*> spliter;

    stringstream text(words);

    /*
    while(getline((text), words, ' ')) {
        spliter.push_back(words.c_str());
    }
    */

    ctokenize(text, spliter);

    for(auto x:spliter) {
        cout << x << " ";
    }
    cout << endl;

    auto cstr_compare = [](const char* s1, const char* s2) {
        return strcmp(s1,s2) < 0;
    };

    sort(spliter.begin(), spliter.end(), cstr_compare);

    for(auto x:spliter) {
        cout << x << " ";
    }
    cout << endl;

    return 0;
}