无法从'std :: string'转换为'char'

sir*_*isp 1 c++ arrays sorting

由于其他成员的建议,完全改变了.大多数问题解决了,仍有问题.现在不会从main中的数组中输出任何名称.不确定我是否正确地将它们从功能上传回去了.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void bubblesort(string[], const int);
int sub = 0;

int main()
{
const int maxsize = 100;
string friendArray[maxsize];

ifstream friends;
friends.open("myFriends.dat");

while (sub < maxsize)
 {
  getline(friends, friendArray[sub]);
  sub++;
 }

 bubblesort(friendArray, maxsize);


 cout<<friendArray[0]<<" "<<friendArray[1]<<" "<<friendArray[2];

 system("pause");
 return 0;
}



void bubblesort(string *array, const int size)
{
    bool swap;
    string temp;

    do
    {
        swap = false;
        for (int count = 1; count < (size - 1); count++)
        {
            if(array[count-1] >array[count])
            {
                temp = array[count-1];
                array[count-1] = array[count];
                array[count] = temp;
                swap = true;
            }
        }
    }
    while(swap);

}
Run Code Online (Sandbox Code Playgroud)

Aus*_*oke 5

你的问题不一定是temp内部bubblesort不是a char,问题array是声明为a string而不是a string[].

您收到错误的原因是因为array[count+1]类型chartemp类型string.std::swap期望两个相同类型的元素.

但是,这可能是您遇到的问题中最少的,您的代码由于很多原因而无法编译.不仅如此,但你正在传递maxsizebubblesort每个迭代.你的逻辑和语法都存在缺陷.

编辑:由于您仍然无法使排序工作,这里是您的代码的工作修改:

#include <iostream>

void bubblesort(std::string array[], size_t size)
{
  bool bSwapped;
  std::string temp;

   do
   {
      bSwapped = false;
      for (size_t count = 1; count < size; count++)
      {
         if(array[count-1] > array[count])
         {
            std::swap(array[count-1], array[count]);
            bSwapped = true;
         }
      }
   }
   while(bSwapped);
}

int main(void)
{
   std::string array[] = { "def", "ghk", "abc", "world", "hello" };

   bubblesort(array, sizeof(array)/sizeof(*array));

   for (size_t i = 0; i < sizeof(array)/sizeof(*array); ++i)
      std::cout << array[i] + " ";

   std::cout << std::endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

bubblesort也可以写成:void bubblesort(std::string *array, size_t size).在这种情况下没有区别,因为当传递给函数时,数组会衰减为指针.

由于数组是通过引用传递的,指向第一个元素的指针,对其array内部进行的任何修改bubblesort实际上都将修改您的数组main.这就是阵列"返回"的方式.

std::vector是标准数组的一个很好的替代品,因为它会自动调整大小并显然包含内部数组的长度,这样您就不必在传递的任何地方传递大小std::vector.您也可以像使用常规数组一样使用它.