Monday 13 August 2018

c++ - vector in function - how to do return

Well, you are trying to return a vector as strings. This won't work because they are different types and have no conversion defined from one to the other. Your function has the return type string.



Solution 1



In your case you could append the lines to a string instead of adding them to a vector? You are using the result as a string anyhow.




You could change seqs to string and append data to it with the += operator.



Solution 2



You could also change the return type to vector but you would need to loop over the items and print them instead in your main.



vector getseq(char * db_file)
{
...
return seqs;

}


Caveat Lector: this will copy all the items. If you want to avoid this pass the vector as a reference to the function and add to it.



Looping is quite easy using iterators:



// Get the strings as a vector. 
vector seqs = getseq(argv[1]);


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

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






If you want to avoid copying a vector and all the strings make getseq take a reference to a vector.



void getseq(char * db_file, vector &seqs)
{
...
// vector seqs; this line is not needed anymore.

...

// we don't need to return anything anymore
}


You would then need to create the vector in your main instead, making my above code:



// Get the strings as a vector. 
vector seqs; // Holds our strings.
getseq(argv[1], seqs); // We don't return anything.


// This is just a matter of taste, we create an alias for the vector iterator type.
typedef vector:iterator_t 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;





Edit after comments



int main(int argc, char * argv[1])

{
// This is what you need, sorry for the confusion.
// This copies the vector returned to seqs
vector seqs = getseq(argv[1]);

// This is just a matter of taste, we create an alias for the vector iterator type.
typedef vector::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;
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...