如何在C ++中按字母顺序将字符串存储在向量中?

时间:2016-09-01 03:47:20

标签: c++

我想按以下顺序将一个字符串数组存储到一个两个暗淡的向量中。

    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]);
        }

    }
}

但是我遇到了一些访问冲突错误。请帮帮我。

3 个答案:

答案 0 :(得分:2)

您应该使用ASCII代码将字符转换为整数这一事实。 例如:'A' = 65。 因此,您可以使用它来获取元素需要插入的索引值。要运行以下代码,您必须包含toupper函数的<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]);
}

答案 1 :(得分:0)


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;

        }
    }
}

答案 2 :(得分:0)

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.
    }
}