如何在Vector中按字母顺序存储字符串

How to Store Strings in a Vector in Alphabetical Order in C++?

本文关键字:顺序存储 字符串 Vector      更新时间:2023-10-16

我想按照以下顺序将字符串数组存储到一个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;
        }
    }
}