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


ADVERTISEMENT

C++ :: How To Access Certain Elements And Store Multiple Inputs

Jan 20, 2014

am trying to create a program that asks the user personal questions.

std::vector<std::string> name, age, favsinger;
std::cout << "Hello, what is your Name Age Favorite_Singer? ";
std::cin << name; //i want to store the user's info along with the sibling's

[Code]....

View 4 Replies View Related

C++ :: Read 100 Elements From Standard Input Device And Store Them In Array

Feb 19, 2014

Write code to do the following:

1) declare a variable ptr as a pointer to int and initialize it to NULL
2) dynamically allocate memory for an array of 100 elements
3) read 100 elements from the standard input device and store them in the array.

This is what I have so far, I'd like to know if its ok or if something is wrong.

int *ptr = NULL;
ptr = new int[100];
cin >> dataPtr [arr];

View 2 Replies View Related

C++ :: Class Memory Allocation - Store Number Of Elements In Table

Mar 31, 2013

Say I have a class with a few member functions, and only two data members: an int* Table; and an int Size;, to store the number of elements in Table.

I'm using a copy constructor that takes in two parameters: int* table, int size. In this case, is the address that table points to the same address as the object that table is part of? And furthermore, is it possible to say table.Size? I want to compare the passed array's size to the passed size.

View 2 Replies View Related

C++ :: Read Float Numbers From Keyboard And Store Them Into Array Of 10 Elements

Jan 10, 2013

I have to complete a project that i want to read float numbers from keyboard and store them into an array of 10 elements.! Every time that a number stored into array i want to compare with previous one if they have +-10 difference .. I want to keep only 10 elements into my array so every time that i give value a[0] replace a[1], a[1] replace a[2],a[2] replace a[3]. . . .and a[10] deleted.. So when all elements of the array are similar with +-10 values print out the array.!

View 1 Replies View Related

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 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++ :: Function Call That Moves Entity From One Vector To Another

Nov 15, 2014

Ok so I have a function call that moves an Entity from one vector to another, and if one doesn't exist then it creates one and moves it:

std::vector<std::unique_ptr<Entity>> ActiveEntities;
std::vector<std::unique_ptr<Entity>> EntityPool;

// Creates a generic entity in the entity pool
void EntityManager::CreateEntity() {

[Code] .....

In this case it checks the entity pool for an entity, if one exists it moves it to the active entities and then returns the unique id, if one doesn't exist it creates one then calls itself to run the check again to verify and move the new entity.

My question is, is this a valid form of recursion since it only incurs a single loop of recursion, or should I reform the entire system to work differently? If so, how do you set this up in a way that does not cause recursion?

View 3 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/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++ :: Split A String And Store Into 2D Vector

Oct 14, 2014

I am having trouble with parsing out string value into a 2D vector. Suppose i have the string "attack at dawn " consisting of 15 characters, i will like to store it into a 2D vector with 5 rows and 3 columns and the result is as follow.

Vector[0][0] = "a"
Vector[0][1] = "t"
Vector[0][2] = "t"
Vector[1][0] = "a"
Vector[1][1] = "c"

[Code] ....

View 1 Replies View Related

C/C++ :: Split A String And Store Into 2D Vector

Oct 13, 2014

I am having trouble with parsing out string value into a 2D vector. Suppose I have the string "attack at dawn " consisting of 15 characters, i will like to store it into a 2D vector with 5 rows and 3 columns and the result is as follow.

Vector[0][0] = "a"
Vector[0][1] = "t"
Vector[0][2] = "t"
Vector[1][0] = "a"
Vector[1][1] = "c"
Vector[1][2] = "k"
Vector[2][0] = " "
Vector[2][1] = "a"
Vector[2][2] = "t"
etc...

Here is a draft code that i did but is not working as desired.

vector<vector <string > > plaintextVector;
vector<string> row;
string totalString = "attack at dawn ";
int dimension = 3;

[Code] ....

View 4 Replies View Related

C/C++ :: Call To Move Constructor When Vector Pushback Is Called

Dec 29, 2014

#include <vector>
#include <iostream>
#include <iterator>

[Code]....

I am confused for first call to push_back copy constructor is called for second call I am expecting it to move class instance to new memory location there by trigering move and then inserting second class instance expected call:

Copy constructor
Move constructor
Copy constructor
but its calling
Copy constructor
Copy constructor
Move constructor

View 6 Replies View Related

C++ :: Nested Vector Initialization - No Matching Function For Call

Jun 26, 2013

I initialized a nested vector with the following code as:

Code:
vector<vector<Point> > vectorB(4, vector<Point> (int(vectorA.size()), 0));

And came across the following error during link stage:
"/usr/include/c++/4.6/bits/stl_vector.h:1080:4: error: no matching function for call to ‘std::vector<cv::Point_<int> >::_M_fill_initialize(std::vector<cv::Point_<int> >::size_type, int&)’ "

View 6 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++ :: Can't Store Different Values Into Vector By User Input

May 4, 2013

I can`t seem to store multiple values into my vector when a user keys in an input. Lets say a user inputs 1,2 as the first set and later keys in 3,4.

My vector gets overridden by 3 and 4. I'm trying to pass these values into a function to store them into a vector and use them in the function.

Below is my code snippet

int reconstructSecret(int x, int y) {
int getX,getY;
getX=x;
getY=y;
vector<int> myXCordVec;
vector<int> myYCordVec;

[Code] .....

View 6 Replies View Related

C++ :: Compare Data Members Of Objects Store In Vector

Mar 6, 2014

Overview of problem : I am using std::vector to hold objects of Subject. Now this vector contains lots of objects( with lots I mean 10-20 objects at max) . These objects have string member values like category and sub_category. Both category and sub_category can have string which can be same of other objects's sub_category & category.

Issue: Now I want my std::vector to have only those objects whose's sub_category are unique. If category is not unique that's not a problem .

Secondly if we found 2 objects having same sub_category then we have to delete one of them from the vector. we will delete it based on some rules example

Rules for deleting are if

i) instance of Subject ->category = " Land " OR if category = "Jungle" then delete other duplicate object ,
ii) if above condition doesn't match then delete either of them.

I am wondering , how would I compare the sub-items from the vector . For example. I have class say Subject

class Subject {
public :
// some constructors,
// functions to get ., set category and sub category
std::String get_sub_category()
std::string get_category();
private:
std::string category;
std::string sub_category;
}

I have vector which stores object of Subjects. Example : vector<Subject> copy_vector;

Now what I want is to delete the object from vector that has same sub_category I am not looking for source code buT i need a starting point,? Example:

copy_vector[0] = Animal object that has sub_category Tiger
copy_vector [1] = Animal object with Lion as sub category
copy_vector[2] = Forest object with sub_category Tiger

What I want is to based on some conditions(which I can do ) remove either Forest or Animal object containing Tiger. But for that how would I do comparison? I have written the function and have checked it.

std::vector< Subject >copy_vector;
// copy_vector contains all the objects of Subject with redundant sub_category
for( std::vector< Subject >::iterator ii = copy_vector.begin() ; ii != copy_vector.end() ; ++ii ) {
sub_category = ii->get_sub_category();

[code] ....

View 1 Replies View Related

C++ :: Generate Random Integers In The Range And Store Them In A Vector

Sep 3, 2014

You are to write a C++ program to generate random integers in the range [ LOW = 1, HIGH = 10000 ] and to store them in a vector < int > of size VEC_SIZE = 250. Then, sort the contents of the vector (in ascending order) and display it on stdout.

To sort the contents of a vector, use the sort ( ) function from the STL. In addition to the main ( ) routine, implement the following subroutines in your program:

• void genRndNums ( vector < int >& v ) : This routine generates VEC_SIZE integers and puts them in vector v. Initializes the random number generator (RNG) by calling the function srand ( ) with the seed value SEED = 1, and generates random integers by calling the function rand ( ).

• void printVec ( const vector < int >& v ) : This routine displays the contents of vector v on stdout, printing exactly NO_ITEMS = 12 numbers on a single line, except perhaps the last line. The sorted numbers need to be properly aligned on the output. For each printed number, allocate ITEM_W = 5 spaces on stdout.

Programming Notes:

• You are not allowed to use any I/O functions from the C library, such as scanf or printf. Instead, use the I/O functions from the C++ library, such as cin or cout.
• Let v be a vector of integers, then the call: sort ( v.begin ( ), v.end ( ) ) sorts the elements of v in ascending order. The detailed description of the sort ( ) routine can be found on the course web site and in the course textbook.
• Execute the srand ( ) function only once before generating the first random integer with the given seed value SEED. The rand ( ) function generates a random integer in the range [ 0, RAND_MAX ], where the constant value RAND_MAX is the largest random integer returned by the rand ( ) function and its value is system dependent. To normalize the return value to a value in the range [ LOW, HIGH ], execute: rand ( ) % ( HIGH – LOW + 1 ) + LOW.

View 1 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++ :: Store Coordinates As X And Y In A Vector To Find Nearest Neighbor Of Given Points

Oct 13, 2014

Lets say that i have the coordinates of a 2D space (x and y), I want to store the coordinates as x and y in a vector to find the nearest neighbor of given points like i have:

#3.57 3.18#
#84.91 27.69
#93.40 4.62
#67.87 9.71
#75.77 82.35
#74.31 69.48
#39.22 31.71
#65.55 95.02
#17.12 3.44
#70.60 43.87

Each coordinates is like x y and it shows points 1 to 10 (like 3.57 3.18 is point 1 in 2D space ). My question is that how i add all x and y coordinates in vector? I started like this;

`struct point{
int x;
int y;

[Code] ....

View 1 Replies View Related

C++ :: Store Function To A Variable And Call It Using That Variable?

Oct 15, 2013

I want to store few different functions to a variable for different structs/classes and then call it later using that variable, is it possible? something like

struct item {
int ID;
int special; // for function
};

item Key;
Key.special = UseKey(KEY_KING);

// now when I want to call function "UseKey(KEY_KING)" I want to use "Key.special", like this

if(iCurrRoom == ROOM_KING)
Key.special;
else if(iCurrRoom == ROOM_DRAGON)
Fireball.special;

View 5 Replies View Related

C++ :: Program Should Input Each Student Grade As Integer And Store Grade In Vector

Jun 26, 2013

I get so close, and then it seems my brain shuts down ... I need to write a program that outputs a histogram of student grades for an assignment. The program should input each student's grade as an integer and store the grade in a vector. Grades should be entered until the user enters -1 for a grade. The program should then scan through the vector and compute the histogram. In computing the histogram, the minimum value for a grade is 0, but your program should determine the maximum value entered by the user. Use a dynamic array to store the histogram. Output the histogram to the console. For example, if the input is:

20
30
4
20
30
30
-1

Then the output should be:

Number of 4’s: 1
Number of 20’s: 2
Number of 30’s: 3

I can't quite get my output to look like that:

/* This program will display the histogram of student grades for an assignment */
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <conio.h>

[code]......

View 3 Replies View Related







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