c++ - void Print(vector<string>) 函数不打印

标签 c++ string vector stdvector cout

<分区>

我创建了一个使用交互器打印 vector 的函数。该函数是程序的一部分,旨在将一个字符串 vector 复制到另一个字符串 vector 。原始函数是一个使用 .at() 成员函数的简单 for 循环,并且有效。所以,我不确定这个有什么问题。 代码:

#include <string>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void print(vector<string> &v);

int main() {
    ifstream inFS;
    inFS.open("sentence.txt");

    vector<string> wordList; vector<string> newVect; 
    string s;
    while (inFS >> s) {
        wordList.push_back(s);
    }

    copy(wordList.begin(), wordList.end(), newVect.begin());
    print(wordList);
    print(newVect);
}


void print(vector<string> &v) {
    for (vector<string>::iterator i = v.begin(); i != v.end(); i++) {
        cout << *i << " ";
    }
    cout << endl;
}

输出:

C:\Users\westt\Documents\PROJECT>a.exe

C:\Users\westt\Documents\PROJECT>

最佳答案

尝试这个简单的改变来初始化 newVect。如评论所述,您还可以 resize() newVect

#include <string>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void print(vector<string> &v);

int main() {
    ifstream inFS;
    inFS.open("sentence.txt");

    vector<string> wordList; 
    string s;
    while (inFS >> s) {
        wordList.push_back(s);
    }

    vector<string> newVect(wordList);
    print(wordList);
    print(newVect);
}


void print(vector<string> &v) {
    for (vector<string>::iterator i = v.begin(); i != v.end(); i++) {
        cout << *i << " ";
    }
    cout << endl;
}

关于c++ - void Print(vector<string>) 函数不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52250319/

相关文章:

javascript - 存在 jQuery 字符串比较问题

r - grep 的优化版本以将向量与向量匹配

c++ - 从 vector 映射中查找并删除 std::function 对象

c++ - 自下而上的方法来找零硬币的最小数量

java - 在 Java 中分解包含姓氏、名字和首字母的字符串

c++ - 这个冒号在枚举声明中做了什么?

java - 从 Java 字符串中去除前导和尾随空格

c++ - `type` 对于 std::vector 而不是 OpenCV 中的 cv::Mat 的解释是什么?我该如何更改它? (C++)

c++ - 如何仅为函数指针编写正确的构造函数?

c++ - QTableWidget 中的 QCheckBox,点击标签不会改变状态