[英]sorting alphanumeric string using vector
我有一個包含字母數字字符串的向量,我想根據數字值對向量進行排序。
例如,如果我的向量包含以下值:
name0 name20 name15 name3 name10,我排序的向量應如下所示:
name0 name3 name10 name15 namw20。
任何人都可以幫忙怎么做..? 這是我完整的代碼:
#include<vector>
#include<string>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
vector<string> temp;
temp.push_back("name0");
temp.push_back("name20");
temp.push_back("name15");
temp.push_back("name3");
temp.push_back("name10");
sort(temp.begin(), temp.end());
for (vector<string>::size_type i = 0; i!= temp.size(); i++)
cout << temp[i] << endl;
return 0;
}
假設使用C ++ 11,則可以使用lambda和std::stoi
將字符串的有效部分轉換為數字。
sort(temp.begin(), temp.end(), [] (const std::string& a, const std::string& b) {
std::string cmp_a { a.begin() + 4, a.end() };
std::string cmp_b { b.begin() + 4, b.end() };
return std::stoi(cmp_a) < std::stoi(cmp_b);
});
當然,如果轉換失敗,則將拋出std::stoi
,因此請確保傳遞給它的字符串僅包含數字。
在C ++ 03中,可以使用Boost.Lexical_Cast
:
int convert(const std::string& s, std::size_t pos)
{
return boost::lexical_cast<int>(s.data() + pos,
std::distance(s.begin() + pos, s.end()));
}
bool predicate(const std::string& a, const std::string& b)
{
return convert(a, 4) < convert(b, 4);
}
如評論中所述, 4
是出現第一位數字的硬編碼位置。 如果變化,則可以使用find_first_of
:
const std::string numbers = "0123456789";
bool predicate(const std::string& a, const std::string& b)
{
std::size_t a_start = a.find_first_of(numbers);
std::size_t b_start = b.find_first_of(numbers);
return convert(a, a_start) < convert(b, b_start);
}
Charles Salvia已經寫了一個更好的答案(它不依賴Boost或C ++ 11)。 他鏈接到實現自然排序順序的頁面,如另一條評論所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.