【发布时间】:2019-12-06 07:14:12
【问题描述】:
我目前在测试我的冒泡排序时遇到了麻烦(我还没有完成它的实际代码)但是当我有字符串向量时:“words[j][j]”并且它没有print ANYTHING while doing "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;
}
另外,变量名只是为了让它工作,不用担心。任何帮助表示赞赏:)
【问题讨论】:
-
你的作业需要使用指针吗?
-
word是指向vector<string>的指针。你需要(*words)[j][j]。但是你真正应该做的是停止动态分配你的向量并传递一个指向它的指针。get_words应该按值返回,bubbleList应该通过引用获取它的参数。
标签: c++ string for-loop vector indexing