如何在Vector中按字母顺序存储字符串
How to Store Strings in a Vector in Alphabetical Order in C++?
我想按照以下顺序将字符串数组存储到一个two dim vector .
String Starts with 'A' or 'a' --> vector[0][]
String Starts with 'B' or 'b' --> vector[1][]
.
.
String Starts with 'Z' or 'z' --> vector[25][]
<------------------- Code---------------------------->
string alphaU = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
string alphaL = "abcdefghijklmnopqrstuwxyz";
string alphsaL ="1234567890123456789012345";
//26 buckets
vector<string> V[26];
//insert element into bucket according to the first alphabet
for (int h = 0; h < 26; h++)
{
for (i = 0; i < size; i++)
{
if (arr[i].at(0) == alphaU.at(h) || arr[i].at(0) == alphaL.at(h))
{
V[h].push_back(arr[i]);
}
}
}
但是我得到一些访问违反错误。
您应该使用可以使用ASCII码将字符转换为整数的事实。例如:'A' = 65
。因此,您可以使用它来获取需要插入元素的索引值。要运行下面的代码,必须包含topper函数的<cctype>
头。
for(int i=0; i<size; i++){
char front = arr[i].at(0);
/* Make Sure that you calculate index by first converting it to upper case*/
int index = (int)(std::toupper(front) - 'A');
v[index].push_back(arr[i]);
}
设string arr[]
的大小为n
;
vector<string> data(26);
for(int i = 0; i < n; i++) {
int idx1 = arr[i][0] - 65;
int idx2 = arr[i][0] - 97;
if( idx1 >= 0 && idx1 < 26 )
data[idx1].push_back(arr[i]);
else if (idx2 >= 0 && idx2 < 26)
data[idx1].push_back(arr[i]);
else {
// I don't know what do you want to do in case of string not starting with alphabets.
}
}
for ( int h = 0 ; h<j ; h++ ) // ordering using two for loops
{
for(int l=0; l<j; l++)
{
if(uniq[l]>uniq[l+1]) //checking if the counter value is bigger or smaller
{
temp = counter[l];
counter[l] = counter[l+1]; //ordering of both string and int
counter[l+1] = temp;
temp_1= uniq[l];
uniq[l] = uniq[l+1];
uniq[l+1] = temp_1;
}
}
}
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 按字母顺序对字符串中的字母进行排序,而无需使用内置的 sort()
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- 如何存储字符串列表
- 在向量中存储字符串存在 SEG 错误
- 指针存储字符串?
- 逐个字母存储字符串并打印
- C 在向量的向量中按字母顺序排序字符串
- 将字符指针按顺序存储在 map 中 std::map<char*, int> mymap。将其存储为字符或字符串不是一个选项
- 按字母顺序对字符串数组进行排序C++
- 将字符数组转换为字符串并存储字符串?
- 在 C++ 中使用链表按字母顺序对字符串进行排序
- 链接列表并按字母顺序插入字符串
- 当分配动态内存以存储字符串副本时,程序会中断
- 在C/C++中存储字符串、数组和指针,哪种方法更有效
- 我们如何以 7 位格式存储字符串
- C 存储字符串输入为CString
- 按字母顺序对 c 字符串数组进行排序
- C++以相反的顺序存储字符串
- 如何在Vector中按字母顺序存储字符串