Friday, 8 December 2017

c++ - how do i add elements to an empty vector in a loop?

itemprop="text">


I am trying to create an
empty vector inside a loop and want to add an element to the vector each time something
is read in to that loop.



#include

#include

using namespace
std;

int main()
{
std::vector
myVector();


float x;
while(cin >>
x)
myVector.insert(x);

return
0;
}


but
this is giving me error messages.



class="post-text" itemprop="text">
class="normal">Answer



You need
to use rel="noreferrer">std::vector::push_back()
instead:



while(cin >>
x)
myVector.push_back(x);
//
^^^^^^^^^


and not
rel="noreferrer">std::vector::insert(), which, as
you can see in the link, needs an iterator to indicate the position where you want to
insert the element.




Also, as href="https://stackoverflow.com/questions/17984268/how-do-i-add-elements-to-an-empty-vector-in-a-loop/17984286#comment26293169_17984268">what
@Joel has commented, you should remove the parentheses in your vector
variable's
definition.



std::vector
myVector;


and
not



std::vector
myVector();



By
doing the latter, you run into C++'s href="https://en.wikipedia.org/wiki/Most_vexing_parse" rel="noreferrer">Most Vexing
Parse problem.


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 ...