C++ :: Filling A Vector With Elements?

Mar 21, 2013

I'm writing a program with a class containing a private std::vector<bool>. I chose bool because the vector represents a 2D array (think grid) and I only need 2 states per cell. I kept it one-dimensional as this hardly complicates things.

My problem is that I don't know how to initialize the vector, i.e. fill it with 0's.

The grid's resolution is not known at compile time, so I imagine I have to set the size (and content) of the vector in the class constructor.

Here's what I have tried among several things:

Code: World::World(const u_short worldsize)
{
grid.reserve(worldsize * worldsize); // grid is the private vector; square dimensions.
std::fill(grid.begin(), grid.end(), 0);
std::cout << grid.size();
} The output is 0. Only std::vector::push_back seems to have an effect on size(), but judging by its description, it doesn't look like the right candidate to populate a vector with zeros. Correct me if I'm wrong.

Frankly I expected line 3 to set the vector's size.

View 5 Replies


ADVERTISEMENT

C++ :: Filling A Vector With Structs

Feb 1, 2013

How to fill a vector with structs that are read in from a separate file. Each line in the file would read for example "Doe John M 26" for the name of the person, gender and age. I just need to get pointed in the right direction so I can get this started.

View 2 Replies View Related

C++ :: Filling Vector From A File - Adding Empty Element At The End

Apr 20, 2014

I'm having a problem filling a vector from a file. Basically, it is adding an empty element at the end. I'm new to Qt and haven't worked with file streams much so how to stop the stream before it adds the extra element.

void gui::get_data() {
mileage.clear();
QFile file(file_label->text() + ".txt");
QTextStream in(& file);
float m;
float g;
QString d;

[Code] ....

But, if I add another element to the vector and write that the file look like this.

//file after adding element
132654 0 02132014
132654 0 02132014
0 0
132998 22 02202014

I have it set to append at the moment so that is why the first line is repeated. I figure the problem is with if(in.atEnd()). I could fix it by deleting the last element right after adding it, but that seems like more of a hack than anything else.

View 3 Replies View Related

C++ :: Swap Elements Of Vector

Apr 21, 2014

how to swap the first and 'mid' elements of a vector?

View 2 Replies View Related

C++ :: Generating All Possible Combinations Of Vector Elements

Feb 14, 2013

I have an integer vector of size "n".

e.g.
std::vector<int> vec;
vec.pushback(0);
vec.pushback(1);
vec.pushback(2);
vec.pushback(3);

Now I want to generate all possible combinations of size = {0, 1, 2, ... , n}.

{0, 1, 3} is not equal to {3, 1, 0} or {1, 0, 3} or {3, 0, 1}

View 7 Replies View Related

C++ :: Memory Size Of Vector Elements

Apr 9, 2014

I had a question about memory allocation/how iterators work for a std::vector<foo> of a user defined class 'foo'. Say foo contains variables of variable size, so that each member of the std::vector<foo> does not require the same amount of memory space.

Does c++ allocate the same amount of memory for each element, equal to the amount of memory required for the largest element? Or does it use some sort of array of pointers pointing to the location of each element in the vector to make the iterator work? Or does it use some other method? I am wondering because I wrote a code which reads data from a binary files and stores most of it in std::vectors.

The code seems to be using significantly more memory than the sum of the size of all the binary files, and I am using vectors made up of the datatype within the binary files (float). So I was wondering if internally the code was allocating space for each vector element which is the size of the largest element as a way to handle indexing/iterators. I ran my code through a memory leak checker and it found no errors.

View 16 Replies View Related

C++ :: How To Store Elements In 2D Vector And Call Them Out

May 5, 2013

I am currently trying to implement a 2d vector to store x and y of type int.

I have successfully passed it to the function, however i am unable to store the values in it. It always returns with a segmentation fault and my program terminates from there. May i know how do i store them properly and call them out?

Below is my code snippet

int reconstructSecret(int x, int y, vector< vector<int> > &inVec ,int constructSecret) {
int getX,getY,formula,accum,count,getSecret,startPosition,nextPosition,numerator,denominator;
getX=x;
getY=y;
int result;

[Code] .....

The main method

vector< vector<int> > inVec;
for(int i=0;i<constructSecret;i++) {
cout<<"please key in the "<<i<< "share of x value:";
cin>>x;

[Code] ...

View 9 Replies View Related

C/C++ :: Erasing / Removing Elements From A Vector?

Mar 23, 2015

I am working on a project for class where I use a parent Shape class with circle, rectangle, ect. Classes inheriting from that. Along side these I use a class called Scene. In main I need to create a scene and add some shapes to a vector in scene.

vector<Shape*> shapes

I need to use functions addShape(Shape* shape) and a delete shape method. I have the addShape finished. The problem I am having is with the delete method. Is there a way that I can use something like deleteShape(Shape* shape)? Is it possible for me to delete a specific shape from the vector by passing in that shape, or can it only be done using index? I have looked at the documentation for std::vector as well as std::vector::erase. I am wondering this because if I use index values and do something like

void Scene::deleteShape(unsigned int x) { shapes.erase(shapes.begin() + x ); }

It will lead to some errors later on due the the changing size and indexes of the vector and elements.

View 4 Replies View Related

C++ :: Accessing Nested Elements Of Vector

May 1, 2015

so lets assume i have a nested vector in a set or vice versa o in a more general form a container in a container example...

Code:
std::set<vector<int> > my_tuple;

How do i access individual elements of lets say the first vector in the set! Or the last element in the 3rd vector?

View 7 Replies View Related

C++ ::  How To Print Out Elements Of Vector Of Type Pair

Oct 7, 2014

here is a piece of my code:

while(T--)
{
std::vector<std::pair<int, int> > *dragon;
std::vector<std::pair<int, int> > *villager;

[Code]....

I now wish to print the elements of the vector. How do I do it?

View 2 Replies View Related

C++ :: Vector Whose Elements Have Function Pointer Type

Mar 30, 2013

"Write a declaration for a function that takes two int parameters and returns an int, and declare a vector whose elements have this function pointer type."

View 9 Replies View Related

C/C++ :: Insert Number Of Elements From One Into Another Vector Without Resizing

Dec 28, 2012

I think std::copy appears to do what I'm looking for.

I'm in need of a vector member function that would allow me to "insert" a number of elements from one vector into another vector without resizing or destroying either.

An example of what I'm wanting to do is assign the contents of two[3-5][50-54] to one[7-9][2-6]. Other than looping through both vectors using .at(), is there a way to copy this?

This would be continuous within a user controlled loop with differing elements being exchanged.

typedef vector<vector<unsigned char> > vec;  
vec one(10, vector<unsigned char>(10, '1')),
    two(90, vector<unsigned char>(90, '2'));  

View 4 Replies View Related

C++ :: Searching STD Vector Of Strings - Counting Matching Elements And Erasing Them

Jul 19, 2013

I have read that the Erase-remove idiom is the way to go. I have a rough understanding of how this works but am unsure whether I can implement a match-counter along with it.

For counting alone, I would use something like this:

Code:
std::vector<std::string> v; // contains duplicate strings in different elements
std::string term = "foo"; // search term, changing at runtime as well

unsigned int matches = 0;
for( auto e : v ) {
if( e == term ) {

[Code] .....

I'm not sure how (or if) I can combine the two things. That is, I don't know how to integrate a function comparing two (changing) strings into the remove_if() method. Nor do I know how to increment a counter during iteration.

The vector is extremely large, so speed is paramount. I think there are many other avenues for optimization, but decreasing the vector's size for each consecutive search could deliver a big speed boost for subsequent searches I imagine, as traversing it holds the biggest cost.

View 3 Replies View Related

C++ :: Write Swap Function To Swap 2 Elements In Vector?

Nov 15, 2013

write a swap function to swap 2 elements in the vector?

View 3 Replies View Related

C++ :: List Of Vectors (vector Of N Vectors Of M Elements)

Mar 19, 2014

I create a list of vectors (a vector of n vectors of m elements).

std::vector <std::vector <int> > vsFA (n, std::vector<int>(n));

How I assign values? I try below, but not worked

void armazenaFA( std::vector <int> &vFA) // this function only knows about vFA
{ vsFA[n] [m]= simTime().dbl();
OR
vsFA[n].push_back(simTime().dbl());
}

View 1 Replies View Related

C :: Filling 2D Array

Mar 24, 2013

So here is the C code:

Code:

#include <stdio.h>
int main(void)
{
//2D Array
int array[2][2];
int number = 1;
}

[code]....

The array is not filled incorrectly for some reason, more specifically the first row.The first two cycles of the for loop seem to work correctly. One if the bugs seems to occur on the third. when array[0][2] is filled with number 7, for some reason array[1][0] changes it value to 7 as well.

View 2 Replies View Related

C :: Filling Array With Even And Odd Number

Jun 25, 2013

I have this snippet :

Code:
#include<stdio.h>
#define LEN 3
int main(void)
{
int a[LEN] = {0} , b[LEN] = {0} , i = 0;

[Code] ....

/* OUTPUT :
a[0] = 2 , b[0] = 1
a[1] = 0 , b[1] = 3
a[2] = 0 , b[2] = 0 */

The problem is some elements of the array would be remained zero and unused. Is there any solution about this wasting of memory?

View 7 Replies View Related

C :: Filling 2D Array Complexity?

Mar 24, 2013

Assuming that we have :

Code:
int arr2d[rows][columns] ; // Not valid syntax of course ... let be arr2d rows * columns size
for(int i=0; i<rows; i++)
for(int j=0; j<columns; j++)
arr2d[rows][columns] = some_value;

What is the complexity? I believe O(n) and not O(n^2) on this case because if you have 3*3 size you would put 9 elements (from 9 elements input of course)... for each input you have one insertion and that is the meaning. Same as 4*4 size 16 input times 16 insertions .. or 5*5 and so forth...

View 8 Replies View Related

C :: Filling Float Array

Oct 6, 2013

What am I doing wrong here.

Code:

#include <stdio.h>
#define N 25
int main () {
int s,min,sec,total,mins;
float speed,splits[N];

[Code] ....

View 2 Replies View Related

C++ :: Filling Arrays From A Text File

Jun 20, 2013

I am having a trivial trouble on how to create three different arrays from a text file. I am a beginner in C++. I have a .txt file containing a string of 'float' values as below:

0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.2
1.3

//----------------------

Now, I want to make three arrays, p1[], p2[], and p3[] from them, so that
p1[] has elements from line: 1, 4, 7, ...,
p2[] has elements from line: 2, 5, 8, .., and
p3[] has elements from line: 3, 6, 9,... of the .txt file.

My original file has a huge amount of data, so I would have to use a loop, but I cannot think of a way to fill my arrays as described.

View 3 Replies View Related

C++ :: Initializing / Filling Container With Sample Of Another

May 22, 2014

I have a vector that I want to use to source another vector, something like copy_if, but without the need to allocate space first:

bool is_odd( const int x ){ return x % 2 == 1; }
std::vector< int > numbers = { 1, 2, 3, 4, 5, 6 };
std::vector< int > odd_numbers;
std::sweet_function( numbers.begin(), numbers.end(), odd_numbers, is_odd );
// odd_numbers is { 1, 3, 5 }

Even better might be a std::transform_if

View 5 Replies View Related

C++ :: Filling Int Array Using Binary File

Mar 2, 2013

I am trying to do binary filling. This is the Constructor code, you will see a couple of integer arrays:

Doc::Doc ( int useridValue , string firstnameValue , string lastnameValue , string deptValue
, int dayinhourValue[] , int dayinminValue[] ,int dayouthourValue[] , int dayoutminValue[]
, int timeperpatValue , int appValue[] , int applimValue[] ) {
setuserid(useridValue);

[Code] ....

it gives an error:

void Doc::setdayinhour ( intdayinHOUR[] ){
for(int i=0;i<7;i++) {
dayinhour[i]=dayinHOUR[i];//highlighted area
} }

I am using this code for filling:

void main () {
Doc r;
ofstream outDoc("docdata.dat" , ios::out | ios::binary);
if (!outDoc) {
cerr << "File Could Not Be Opened" << endl;

[Code] ....

View 5 Replies View Related

C# :: Filling And Sending A POST Form

Mar 21, 2015

I'm building a project in my free time and in the last part of it I need to fill a form of a website and then 'hit submit', but how it can be done. Btw the form is a 'POST' form so it's harder than a 'GET' one.

View 2 Replies View Related

C Sharp :: Filling In DataTable Using OleDb

Jul 2, 2013

For some reason I am having problems doing this simple task. I just want to run a query in Access to select a field from the table that is "like" the string being inputted.

However, the dataset comes back empty...well not empty, I get a column name but no data. So when I type in

ds.Tables[0].Columns[0].ColumnName

I get the column name coming from the database ("ParcelNumber"). When I run the query inside Access I receive the desired information. But when I try to check for the info in code

ds.Rows[0]

I get "There is no row at position 0".

public DataTable FindFullPNusingPartialPN(string _parcelNumber)  {
                 OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=" + ConfigurationManager.AppSettings["TaxCert_Database"]);
DataTable dt = new DataTable();

[Code] ....

View 1 Replies View Related

C++ :: Filling Memory Causes Application Crash

Jul 5, 2012

I have a question about allocating 2MB memory then filling it...

@ Platform:
=> DOS, and application is compiled/linked via Watcom C + DOS32/A (...memory model is "flat" mode)

@ phenomenon:
1. I allocate 2M memory by calloc() function. Then I got "!NULL" and it means allocating 2MB memory is ok( right ? )
2. then I tried to "fill" this 2MB memory by for loop(one byte by one byte) like below:

for( DWORD i=0; i<0x200000; i++) {
*((BYTE *)(A[0].B[0]->C) + i ) = 0x5A; // C is 4-byte address value
}

here :
* DWORD means "unsigned long(4-byte)" and 0x200000 means "2MByte"
* in actual case the value of pointer(to allocated memory) is 3019AF3C(~768MB) <- running in flat mode...

3. after filling this range of memory(2MB) the application crashed...

@ my observations:
1. if allocating 2MB and no fill(no write data to memory) => OK
2. if allocating 2MB and just fill the former 32 bytes => OK
3. if allocating 4KB and fill all => OK

my question is: why can't I filling this 2M memory totally "even memory allocation succeeds" ?

View 5 Replies View Related

C :: Word Search Program - Filling 2D Array

Oct 5, 2014

I am currently working on writing a word search program. However, I am stuck on reading the used input into the 2-D array. The code I've posted below is only dealing with the user input (I'll work on the word search part once I know i am correctly reading in the user input). I know the coding is bad practice with the use of hexadecimal, and getchar() ect. But I am currently using a microblaze microprocessor and this is just the way microblaze can interpret the information. As for the infinite while loops...that can be changed just trying to figure out how.

My question is how could I change my code to correctly read in the user input into the 2-D array?

Code:
#include "platform.h"#include "xparameters.h"
#include <stdlib.h>
#include <stdio.h>
#define MAX 20
int main() {
char grid[MAX][MAX], word[30];
int i, j, arr[2],num;

[Code] ....

View 10 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved