【问题标题】:Why is the Vector array printing the memory addresses instead of the array values and why do I get an access violation in my sorting functions? [closed]为什么 Vector 数组打印的是内存地址而不是数组值,为什么我的排序函数会出现访问冲突? [关闭]
【发布时间】:2021-01-16 14:19:03
【问题描述】:

我正在开发一个程序,它可以读取文本文件并将单词存储在一个可以排序然后搜索的数组中。我已经尝试使用动态分配的数组将单词从文本文件中放入,但我得到的只是字符串无法从我的 getline 读取错误(当我使用向量时不会发生这种情况)。当我尝试打印出向量数组以查看传递给排序函数的内容时,它会打印出数组的内存地址,而不是数组中存储的值。

在我将向量数组传递给排序函数后,我的排序函数中的某些点也出现读取访问冲突,但我不明白为什么。我确实在代码中显示了问题所在。请注意,我对编码很陌生,这个程序还远未完成。我包含了到目前为止我所做的所有代码,因为如果我只显示问题区域,我认为我无法理解为什么会出现这些错误。感谢您提供任何帮助。

 #include "flore0900header.h"

int main()
{
    string name;
    int num = 0, num2 = 0, count = 0;
    vector<string> word; //to pass vector array to another function

    cout << "Hello. Enter your name: ";
    cin >> name;
    cout << endl;
    cout << "Welcome " << name << " This program lets you test 5 different sorting algorithms using texts files" << endl;
    cout << endl;
    cout << "Which text file would you like to search?" << endl;
    cout << "=========================================" << endl;
    cout << "1. The Blue Hotel" << endl;
    cout << "2. 20,000 Leagues Under the Sea" << endl;
    cout << "3. A Tale of Two Cities" << endl;
    cin >> num;

    count = text_select(num);
    catch_array(&word); //passing vector array by reference. '&' is there because it won't work otherwise
    cout << endl;
    cout << "Which sorting algorithems would you like to use?" << endl;
    cout << "========================================" << endl;
    cout << "1. Selection" << endl;
    cout << "2. Bubble" << endl;
    cout << "3. Insertion" << endl;
    cout << "4. Merge" << endl;
    cout << "5. Quick" << endl;
    cin >> num; cin >> num2;

    sort_select(num, &word, count);//'&' is there because it won't work otherwise
    sort_select(num2, &word, count);//'&' is there because it won't work otherwise

    cout << endl;
    cout << "Ok! Running algorithms..........." << endl;
}

头文件

#ifndef FLORE0900HEADER_H
#define FLORE0900HEADER_H

#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <istream>
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <ostream>
/* some of the includes are not needed, I haven't removed the un-needed ones yet*/

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;

void selection_sort(vector<string> a[], int size);
void bubble_sort(vector<string> a[], int size);
void insertion_sort(vector<string> a[], int size);
void merge_sort(vector<string> a[], int from, int to);
void quick_sort(vector<string> a[], int from, int to);
int text_select(int num);
void sort_select(int num, vector<string> a[], int size);
vector<string> catch_array(vector<string> a[]);
void merge(vector<string> a[], int from, int mid, int to);
int min_position(vector<string> a[], int from, int to);
int partition(vector<string> a[], int from, int to);
void swap(int& x, int& y);
void print(vector<string> a[], int size);

#endif

text_select 函数文件

#include "flore0900header.h"
//#include <vector>

int text_select(int num)
{
    int count = 0;
    vector<string> words(100000);
    //vector<string>* word2 = new vector<string>[count];
    
    std::ifstream infile;

    if (num == 1)
    {
        infile.open("blue_hotel.txt");
        if (infile.is_open())
        {
            cout << "file is open" << endl;
            getline(infile, words[count]);//string read error when using not using vector
            while (!infile.eof())
            {
                infile >> words[count];
                count++;
                infile.ignore();
                getline(infile, words[count]);
            }
        }
        else
        {
            cout << "file didn't open" << endl;
            exit(1);
        }
    }
    else if (num == 2)
    {
        infile.open("2under.txt");
        if (infile.is_open())
        {
            cout << "file is open" << endl;
            getline(infile, words[count]);
            while (!infile.eof())
            {
                infile >> words[count];
                count++;
                infile.ignore();
                getline(infile, words[count]);
            }
        }
        else
        {
            cout << "file didn't open" << endl;
            exit(1);
        }
    }
    else if (num == 3)
    {
        infile.open("2city10.txt");
        if (infile.is_open())
        {
            cout << "file is open" << endl;
            getline(infile, words[count]);
            while (!infile.eof())
            {
                infile >> words[count];
                count++;
                infile.ignore();
                getline(infile, words[count]);
            }
        }
        else
        {
            cout << "file didn't open" << endl;
            exit(1);
        }
    }
    else
        cout << "not a valid choice try again" << endl;
    infile.close();
    catch_array(&words);//if I don't use '&' the vector won't pass through 
    return count;
}

vector<string> catch_array(vector<string> a[])
{
     return *a;//if I don't put '*' before the 'a' I get an error
}

排序选择文件

#include "flore0900header.h"

void sort_select(int num, vector<string> a[], int size)
{
    int from = 0;

    if (num == 1)
    {
        selection_sort(a, size);
    }
    else if (num == 2)
    {
        bubble_sort(a, size);
    }
    else if (num == 3)
    {
        insertion_sort(a, size);
    }
    else if (num == 4)
    {
        merge_sort(a, from, size);
    }
    else if (num == 5)
    {
        quick_sort(a, from, size);
    }
    else
        cout << "not a valid pick try again" << endl;
}

selection_sort 文件

#include "flore0900header.h"

void selection_sort(vector<string> a[], int size)
{
    int next;
    for (next = 0; next < size - 1; next++)
    {
        print(a, size);//to see what is being passed to the function
        int min_pos = min_position(a, next, size - 1);
        swap(a[next], a[min_pos]);
    }
}

int min_position(vector<string> a[], int from, int to)
{
    int min_pos = from;
    for (int i = from + 1; i <= to; i++)
    {
        if (a[i] < a[min_pos])//read access violation happens here
        {
            min_pos = i;
        }
    }
    return min_pos;
}

void print(vector<string> a[], int size)
{
    
    for (int i = 0; i < size; i++)
    {
        cout << &a[i] << " ";//is printing memory locations instead of values
    }
    cout << endl;
}

冒泡排序文件

#include "flore0900header.h"

void bubble_sort(vector<string> a[], int size)
{
    for (int i = 0; i < size - 1; i++) //loop for recording no# of iteration needed to complete the sorting
    {
        int flagForSwap = 0; //creates a flag variable that accounts for wheather the swap function is called at all

        //loop for counting comparisons
        for (int j = 0; j < size - 1 - i; j++)
        {
            if (a[j] > a[j + 1]) //(read access violation happens here) compare adjacent array elements
            {
                swap(a[j], a[j + 1]); //completes the swap
                flagForSwap = 1; // flag to 1 if swap is used
            }
        }

        if (flagForSwap == 0) //breaks the iteration loop if inputed array is already sorted and no swap is needed
        {
            break;
        }
    }
}

void swap(int& x, int& y)
{
    int temp = x; //creates a temp variable to store the value of the current element
    x = y; // change the value of the current element to next element
    y = temp; //assigns the value of temp to next element
}

插入排序文件

#include "flore0900header.h"

void insertion_sort(vector<string> a[], int size)
{
    for (int i = 1; i < size; i++)
    {
        vector<string> next = a[i];//read access violation happens here
        int j = i;
        while (j > 0 && a[j - 1] > next)
        {
            a[j] = a[j - 1];
            j--;
        }
        a[j] = next;
    }
}

合并排序文件

#include "flore0900header.h"

void merge_sort(vector<string> a[], int from, int to)
{
    if (from == to)
    {
        return;
    }
    int mid = (from + to) / 2;
    merge_sort(a, from, mid);
    merge_sort(a, mid + 1, to);
    merge(a, from, mid, to);
}

void merge(vector<string> a[], int from, int mid, int to)
{
    int n = to - from + 1;
    vector<string>* b = new vector<string>[n];
    int i1 = from;
    int i2 = mid + 1;
    int j = 0;
    while (i1 <= mid && i2 <= to)
    {
        if (a[i1] < a[i2])//read access violation happens here
        {
            b[j] = a[i1];
            i1++;
        }
        else
        {
            b[j] = a[i2];
            i2++;
        }
        j++;
    }
    while (i1 <= mid)
    {
        b[j] = a[i1];
        i1++;
        j++;
    }
    while (i2 <= to)
    {
        b[j] = a[i2];
        i2++;
        j++;
    }
    for (j = 0; j < n; j++)
    {
        a[from + j] = b[j];
    }
    delete[] b;
}

快速排序文件

#include "flore0900header.h"

void quick_sort(vector<string> a[], int from, int to)
{
    if (from >= to)
    {
        return;
    }
    int p = partition(a, from, to);
    quick_sort(a, from, p);
    quick_sort(a, p + 1, to);
}

int partition(vector<string> a[], int from, int to)
{
    vector<string> pivot = a[from];
    int i = from - 1;
    int j = to + 1;
    while (i < j)
    {
        i++;
        while (a[i] < pivot)//read access violation happens here
        {
            i++;
        }
        j--;
        while (a[j] > pivot)
        {
            j--;
        }
        if (i < j)
        {
            swap(a[i], a[j]);
        }
    }
    return j;
}

【问题讨论】:

  • 代码之母!请将您的代码压缩为minimal reproducible example。逐行阅读不相关的代码很痛苦。创建 MRE 的练习会迫使您查看代码并尝试隔离问题,这通常可以帮助您找出问题,甚至无需询问 SO。既然您是新来的,请同时拨打tour,并阅读How to Ask 和what's on-topic here。欢迎使用 Stack Overflow!
  • "sort_select(num, &word, count);//'&' 之所以存在,是因为不然不行” 猜测编程是行不通的。跨度>
  • 为什么sort_select 采用向量数组?
  • 这个网站的代码太多了。您需要将问题缩小到具体问题,然后以minimal reproducible example 的形式向我们展示。祝你好运!
  • 人们不厌其烦地浏览所有不相关的代码这一事实说明了一些真正的无聊。

标签: c++ arrays function vector


【解决方案1】:

没有“向量数组”这样的东西。

你可以拥有向量数组,但你没有。

然而,在这里,你的函数是这样写的:

int partition(vector<string> a[], int from, int to)
//                            ^^

我想这是因为在您在此处添加 [] 和在此处添加 &amp; 之前,您的函数似乎没有做任何事情。

那是因为你是按值传递向量,所以函数中的更改是对副本进行的,因此不会反映在调用范围中。

您的更改允许代码编译,甚至可能在某些晦涩的情况下“工作”,但这只是偶然; [INDEX] 语法在向量和数组之间共享。但是你没有数组,所以假装你做的函数是错误的。您的大部分访问权限都超出范围。

还要注意,如果您没有在某处定义 bool operator&lt;(const vector&lt;string&gt;&amp;, const vector&lt;string&gt;&amp;),它不会编译。

无论如何,使用你的一个向量的解决方案很简单:

  1. 摆脱那个[]
  2. 摆脱那个&amp;
  3. 将现在的 vector&lt;string&gt; 更改为 vector&lt;string&gt;&amp;。 &amp; 的意思是“参考”。

【讨论】:

  • 非常感谢您指出这一点。我没有意识到我使用了错误的语法,因为直到我编译代码以检查它是否正常工作之后编译器才抱怨。这一更改解决了我遇到的问题。
  • 不为努力而投票是不礼貌的(当然这是正确的答案)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
相关资源
最近更新 更多