gpt4 book ai didi

c++ - 函数中的 vector - 如何返回

转载 作者:IT老高 更新时间:2023-10-28 23:16:44 25 4
gpt4 key购买 nike

我有一个函数应该逐行读取文件,当一行不以'>'或''开头时读取停止。它应该将行存储在 vector 中并返回它。
这是代码:

    #include <cstdlib>
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include <vector>

using namespace std;

string getseq(char * db_file) // gets sequences from file
{
string seqdb;
vector<string> seqs;
ifstream ifs(db_file);
string line;

//vector<char> seqs[size/3];

while(ifs.good())
{
getline(ifs, seqdb);
if (seqdb[0] != '>' & seqdb[0]!=' ')
{
seqs.push_back(seqdb);
}
}

ifs.close();
//return seqs;

//return seqs;
}

int main(int argc, char * argv[1])
{
cout << "Sequences: \n" << getseq(argv[1]) << endl;
return 0;
}

编译器 (g++) 返回:

    fasta_parser.cpp: In function ‘std::string getseq(char*)’:
fasta_parser.cpp:32: error: conversion from ‘std::vector<std::basic_string<char, `std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >’ to non-scalar type ‘std::string’ requested`

有人知道吗?

编辑:正如 Skurmendel 所问,由于内存安全违规,我正在添加整个代码

执行编译代码:

#include <cstdlib>
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include <vector>

using namespace std;

vector<string> getseq(char * db_file) // pobiera sekwencje z pliku
{
string seqdb;
vector<string> seqs;
ifstream ifs(db_file);
string line;

//vector<char> seqs[size/3];

while(ifs.good())
{
getline(ifs, seqdb);
if (seqdb[0] != '>' & seqdb[0]!=' ')
{
seqs.push_back(seqdb);
}
}

ifs.close();
return seqs;
}

int main(int argc, char * argv[1])
{
vector<string> seqs; // Holds our strings.
getseq(argv[1]); // We don't return anything.

// This is just a matter of taste, we create an alias for the vector<string> iterator type.
typedef vector<string>::iterator string_iter;

// Print prelude.
cout << "Sekwencje: \n";

// Loop till we hit the end of the vector.
for (string_iter i = seqs.begin(); i != seqs.end(); i++)
{
cout << *i << " "; // Do processing, add endlines, commas here etc.
}

cout << endl;
}

最佳答案

如果我理解你的话,你的 getseq() 应该返回一个字符串 vector 。因此你应该改变

string getseq(char * db_file)

vector<string> getseq(char * db_file)

如果你想在 main() 上打印它,你应该循环执行。

int main() {
vector<string> str_vec = getseq(argv[1]);
for(vector<string>::iterator it = str_vec.begin(); it != str_vec.end(); it++) {
cout << *it << endl;
}
}

关于c++ - 函数中的 vector - 如何返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4885854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com