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

cannot convert from 'std::string' to 'char'

本文关键字:转换 char string std      更新时间:2023-10-16

由于其他成员的建议而完全更改。大部分问题都解决了,还有问题。现在不会在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);
}

您的问题不一定是bubblesort中的temp不是char,问题是array被声明为string而不是string[]

你得到错误的原因是因为array[count+1]的类型是char, temp的类型是stringstd::swap需要两个相同类型的元素

然而,这可能是最不重要的问题,您的代码无法编译的原因有很多。不仅如此,您还在每次迭代中将maxsize传递给bubblesort。你的逻辑和语法都有缺陷。

EDIT:由于您仍然难以使排序工作,这里是对代码的工作修改:

#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;
}

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

由于数组是通过引用(指向第一个元素的指针)传递的,因此对bubblesort中的array所做的任何修改实际上都会修改main中的数组。这就是数组的"返回"方式。

std::vector是标准数组的一个很好的替代方案,因为它会自动调整大小,并且显然包含内部数组的长度,这样您就不必在传递std::vector时到处传递大小。您也可以像使用普通数组一样使用它

temp是字符串,array[count]是char(因为std::string是char元素的vector)。我不知道你在这里想做什么,但编译器是正确的-你不能将char赋值给string。

您可以将temp更改为char,因为您所做的就是为它分配一个char,然后将其分配给数组的一个元素,该元素也是一个char。

您需要将temp声明为char。您可以使用std::swap来避免将来出现这样的错误:

std::swap(array[count], array[count+1]);

这将使您的代码编译,但它不会做你想做的(冒泡排序)。问题是,您传递的是单个字符串(也是字符的"数组"),而不是字符串的数组,这是,在一个非常失落的意义上,"字符数组的数组"。您的冒泡排序需要接受string *array作为其第一个参数。