【问题标题】:Sorting Char Vector排序字符向量
【发布时间】:2017-09-15 07:18:02
【问题描述】:

我正在尝试将估算的字符串转换为 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;

}

【问题讨论】:

  • 为什么在向量中使用char* 而不是std::vector&lt;std::string&gt;?这样你就不需要提供自己的比较函数了。
  • 首先,您显示的代码中没有“字符向量”,但有一个指向char 的指针 向量。其次,为什么你有一个指针向量而不是std::string的向量?
  • 你真的应该使用正确的缩进。我有点难以阅读您的代码。
  • ...也许char的向量更适合用例?
  • 代码格式有点杂乱无章,难以理解。

标签: c++ string vector char


【解决方案1】:

我可以向您推荐这个解决方案吗?

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多