对于循环增量器不能用作字符串向量的索引

For loop incrementer doesn't work as index for vector of strings

本文关键字:不能 字符串 向量 索引 于循环 循环      更新时间:2023-10-16

我目前在测试我的气泡排序时遇到问题(我还没有完成它的实际代码(,但是当我有字符串向量时:"words[j][j]"并且在执行"words[0][0]"时它没有打印任何东西确实打印了一些东西。

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <stdio.h>
using namespace std;
vector<string>* get_words()
{
fstream word_file;
string input;
vector<string>* retval = new vector<string>();
word_file.open("word_list.txt", ios::in);
getline(word_file, input);
while (word_file) {
if (input.length() != 0 && input[0] != '#') {
retval->push_back(input);
cout << input << endl;
}
getline(word_file, input);
}
word_file.close();
return retval;
}
void bubbleList(vector<string>* words)
{
for (int j = 0; j < words->size() - 1; j++) {
cout << words[j][j] << endl; //PROBLEM IS HERE
for (int i = j + 1; i < words->size(); i++) {
}
}
}
void printVector(vector<string>* printer)
{
cout << printer << endl;
}
int main()
{
vector<string>* wordsList;
wordsList = get_words();
bubbleList(wordsList);
return 0;
}

此外,变量名称只是为了让它工作,不用担心。任何帮助都值得赞赏:)

words是一个指针。在指针上使用索引运算符会将其视为数组。例如:

int * i = new int[4];
i[0] = 1; // set the first element of the array
i[1] = 2; // set the second element of the array
i[2] = 3; // set the third element of the array

由于您尚未创建数组,因此您可以访问的唯一索引是第一个元素,这相当于取消引用指针。因此,您的代码应该是:

cout << words[0][j] << "n";

或更传统的:

cout << (*words)[j] << "n";

但是,您根本不需要在代码中使用指针。您可以从get_words中按值返回向量,然后通过引用将其传递给其他函数:

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
std::vector<std::string> get_words()
{
std::fstream word_file;
std::string input;
std::vector<std::string> retval;
word_file.open("word_list.txt", std::ios::in);
std::getline(word_file, input);
while (word_file) {
if (input.length() != 0 && input[0] != '#') {
retval.push_back(input);
std::cout << input << "n";
}
std::getline(word_file, input);
}
word_file.close();
return retval;
}
void bubbleList(std::vector<std::string>& words)
{
for (int j = 0; j < words.size() - 1; j++) {
std::cout << words[j] << "n";
for (int i = j + 1; i < words.size(); i++) {
}
}
}
void printVector(const std::vector<std::string>& printer)
{
for (auto& word : printer)
{
std::cout << word << "n";
}
}
int main()
{
std::vector<std::string> wordsList;
wordsList = get_words();
bubbleList(wordsList);
return 0;
}

指向矢量的指针指向单个向量。因此,循环中的索引具有未定义的行为:

for(int j = 0; j < words->size()-1; j++){
cout << words[j][j]<< endl;             //PROBLEM IS HERE
for(int i = j+1; i < words->size(); i++){
}

您不能在这里使用除 0 以外的任何内容,因为您的新:words[0][j]

首先不明白为什么你需要一个指向矢量的指针。

这里的问题是vector<string>* vec = new vector<string>();vector<string> vec();的动态版本

这不是制作二维向量。当您使用 [0][0] 编制索引时,您不会偏移,这就是它显示的原因。不要将其视为 2d,而是将其视为第一个偏移量为 0 的单个维度:[0][j]

这行代码正在创建一个具有单行和单列的向量,该向量只能在列方向上增长。这就是为什么在索引时必须有 [0][index] 的原因。

vector<string> *retval = new vector<string>();

如果您需要使用指针的 2D 矢量,那么您应该做的是:

vector<string>* vec = new vector<string>[SIZE]();

现在,您有一个向量,您可以使用大于 0 的值为行编制索引。