首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无效打印(vector<string>)函数未打印

无效打印(vector<string>)函数未打印
EN

Stack Overflow用户
提问于 2018-09-10 10:28:27
回答 1查看 202关注 0票数 1

我做了一个使用插入器打印向量的函数。该函数是程序的一部分,用于将一个字符串向量复制到另一个字符串向量。最初的函数是一个使用.at()成员函数的简单的for循环,并且工作正常。所以,我不确定这个有什么问题。代码:

代码语言:javascript
复制
#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;
}

输出:

代码语言:javascript
复制
C:\Users\westt\Documents\PROJECT>a.exe

C:\Users\westt\Documents\PROJECT>
EN

回答 1

Stack Overflow用户

发布于 2018-09-10 10:37:49

尝试这个简单的更改来初始化newVect。正如评论所指出的,您还可以调整newVect ()的大小

代码语言:javascript
复制
#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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52250319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档