Edit object in vector - c++

How can i edit a object in a vector?
Right now my vector is vector<PCB> M3M;
Inside it are a few objects from my class below.
class PCB
{
public:
void setPID (int a)
{
PID = a;
}
int retrievePID()
{
return PID;
}
int retrieveLimit()
{
return Limit;
}
void setLimit (int a)
{
Limit = a;
}
int retrieveBase()
{
return Base;
}
void setBase (int a)
{
Base = a;
}
int retrieveHoleTrueOrFalse()
{
return HoleTrueOrFalse;
}
void setHoleTrueOrFalse (int a)
{
HoleTrueOrFalse = a;
}
private:
int PID;
int Limit;
int Base;
int HoleTrueOrFalse;
};
How would i be able to edit the PID part in any place i choose in my object?
For example i want to set a new PID in my vector at M3M[4]. How do i go about doing that?

M3M[4].setPID(<new PID>);

You also can have an iterator that can point to an element in your array and set a new PID to that. Example:
std::vector<PCB>::iterator it = M3M.begin();
//this will advance your iterator by 3
it += 3;
it->setPID(5); // this will set the 3rd element's PID to 5
Keep in mind that your vector needs to have at least 4 elements in order for the code above to execute. In order to you fill your vector, you can use push_back() method of your vector.
M3M.push_back(PCB(0));
M3M.push_back(PCB(1));
M3M.push_back(PCB(2));
M3M.push_back(PCB(3));
M3M.push_back(PCB(4));

Related

Problems with two-dimensional vector in c++

I'm trying to write a class in c++, that presents a group of people (each person has its own row), and the numbers in the rows represent this person's friends. If person a is person's b friend, then the person b is person's b friend as well.
I came up with something like this:
class Friends {
public:
Friends(int n);
// Creates a set of n people, no one knows each other.
bool knows(int a, int b);
// returns true if the 2 people know each other
void getToKnow(int a, int b);
// Person a & b meet.
void mutualFriends(int a, int b);
// cout's the mutual friends of person a & b
void meeting(int a);
//all friends of person a also become friends
int max();
//return the person with the highest number of friends
private:
vector<vector<int>> friends;
};
Friends::Friends(int n) {
vector<vector<int>> friends;
}
bool Friends::knows(int a, int b) {
for(int i=0; i<friends[a].size(); i++) {
if (friends[a][i]==b) {
return true;
}
}
return false;
}
void Friends::getToKnow(int a, int b) {
friends[a].push_back(b);
friends[b].push_back(a);
}
void Friends::mutualFriends(int a, int b) {
for (int i=0; i<friends[a].size(); i++) {
for (int j=0; j<friends[b].size(); j++) {
if (friends[a][i]==friends[b][j])
cout << friends[a][i] <<", ";
}
}
}
void Friends::meeting(int a) {
for (int i=0; i<friends[a].size(); i++) {
for(int j=0; j<friends[a].size();j++) {
if(i!=j && i!=a && j!=a) {
getToKnow(i,j);
}
}
}
}
int Friends::max() {
int maks = 0;
for (int i=0; i<friends[i].size(); i++) {
if (friends[i].size()<friends[i+1].size())
maks = i;
}
return maks;
}
int main() {
Friends f1 (4);
f1.getToKnow(1,3);
}
So far, every time I try to add something to the vector (f.e. with the function getToKnow) the compiler can't compile the program, pointing that
friends[a].push_back(b);
friends[b].push_back(a);
is wrong. The exact information displayed is "Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)". I don't know what I'm doing wrong and if I'm using the 2d vector correctly.
In the line
Friends::Friends(int n) {
vector<vector<int>> friends;
}
you are creating a local vector of vectors which will be deallocated upon leaving the function.
What you are looking for is:
Friends::Friends(int n) {
friends.resize(n);
}
Which will allocate n vectors, allowing you to access any element below that threshold.
I'm just guessing here, but you should probably create a constructor initialize list to set the size of the member variable:
Friends::Friends(int n)
: friends(n)
{
// Empty
}

How to concatenate name of variables in Cpp?

I have class Walls in my program. Inside of class are objects Wall1, Wall2 etc.
I want to do something like this:
class definition:
class Walls {
public:
Walls(){
nPositionX = nMapWidth - 1;
nHoleSize = 1;
nHolePosition = rand()%(nMapHeight - nHoleSize);
count++;
}
static int getCount() {
return count;
}
int getPositionX()
{
return nPositionX;
}
private:
int nPositionX;
int nHolePosition;
int nHoleSize;
static int count;
};
access to object
for (int i = 0; i < Walls::getCount(); i++) {
int nPosx = Wall"i".getPositionX();
}
}
Is that possible in c++?
Ok big thanks for everyone for help. I don't know why I didn't tried it before.
You can use an array or std::vector for that, eg:
std::array<Wall, MAX_WALLS> m_walls;
or
std::vector<Wall> m_walls;
...
// initialize m_walls[0], m_walls[1], etc as needed...
...
for (size_t i = 0; i < m_walls.size(); i++) {
int nPosx = m_walls[i].getPositionX();
...
}
Or, you can use a std::map, eg:
std::map<std::string, Wall> m_walls;
...
// initialize m_walls["Wall1"], m_walls["Wall2"], etc as needed...
...
for (int i = 1; i <= getCount(); i++) {
int nPosx = m_walls["Wall" + std::to_string(i)].getPositionX();
...
}
The code is not executed until you execute your program, but in the executable there are no variable names anymore. Hence, no.
You can use an array or vector:
struct Wall { int get_position() const { return 42; } };
using Walls = std::vector<Wall>;
Walls walls;
for (const auto& wall : walls) {
int nPosx = wall.get_position();
}
Or if you really want to map names to objects, use a std::map:
std::map<std::string,Wall> named_walls;
named_walls["stone wall"] = Wall();

How to fix the error in C++ vector operation?

The f() function in the class MapSquare works properly.. When I add the other class MapTriple, it is not working. f() function in the MapSquare should find the square of the elements in the vector and in the MapTriple should multiply 3 to all elements.
MapGeneric is the base class which contains the function map() which is a recursive function to access the vector elements and the f() function is a pure virtual function.
MapSquare and MapTriple are two derived classes overrides the f() function to find the square of vector elements and to multiply 3 with all the vector elements.
MapSquare works properly... but when I add MapTriple, segmentation fault occures. Please help to solve this.
#include<vector>
#include<iostream>
#include<cstdlib>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class MapGeneric
{
public:
virtual int f(int){};
vector<int> map(vector<int>, int);
};
class MapSquare:public MapGeneric
{
public: int f(int);
};
class MapTriple:public MapGeneric
{
public: int f(int);
};
class MapAbsolute:public MapGeneric
{
public: int f(int);
};
vector<int> MapGeneric::map(vector<int> v, int index)
{
if(index>=1)
{
v[index]=f(v[index]);
return map(v,index-1);
}
return v;
}
int MapSquare::f(int x)
{
return x*x;
}
int MapTriple::f(int x)
{
return 3*x;
}
int MapAbsolute::f(int x)
{
return abs(x);
}
int main()
{
//mapping square
MapSquare ob;
vector<int> L,L1,L2;
for (int i = 1; i <= 5; i++)
L.push_back(i);
L1=ob.map(L,sizeof(L));
cout<<"Square = ";
for ( vector<int>::iterator i = L1.begin(); i != L1.end(); ++i)
cout << *i<<" ";
//mapping triple
MapTriple t;
L2=t.map(L,sizeof(L));
cout<<endl<<"Triple = ";
for(vector<int>::iterator i=L2.begin();i!=L2.end();++i)
cout<<*i<<" ";
return 0;
}
A number of problems here. It looks as though you think that C++ indices start at 1, rather than zero?
if(index>=1)
{
v[index]=f(v[index]);
return map(v,index-1);
}
To me that immediately looks wrong, surely you mean:
// use size_t for indices (which cannot be negative)
vector<int> MapGeneric::map(vector<int> v, size_t index)
{
// make sure the index is valid!
if(index < v.size())
{
v[index] = f(v[index]);
return map(v, index - 1);
}
return v;
}
Secondly, the sizeof() operator does not do what you expect!! It returns the size of std::vector (which is usually 24bytes on 64 bit systems - basically 3 pointers). You should use the size() method to determine the length of the array.
// remember that indices are zero based, and not 1 based!
L1=ob.map(L, L.size() - 1);

Passing an integer pointer to a constructor and getting runtime memory error

I'm trying to create a vector of a class-name vertex. The value of "n" is not known at compile-time so I'll be using new to create to create the "path" array. But the problem occurs when I create the input array in a function and push it in the vector.
int n;
class vertex {
public:
int *path;
int visited = 0;
vertex(int *y) {
path = new int(n);
for (int i = 0; i < n; i++)
path[i] = y[i];
}
};
void inp(vector<vertex> graph) {
int t1[] = { 0,1,0,0 };
int t2[] = { 0,0,1,0 };
int t3[] = { 0,0,0,1 };
int t4[] = { 0,0,0,0 };
graph.push_back(vertex(t1));
graph.push_back(vertex(t2));
graph.push_back(vertex(t3));
graph.push_back(vertex(t4));
}
int main() {
n=4;
vector<vertex> graph;
inp(graph);
_getch();
}
For simplicity I've created t1 to t4 as static arrays. But still it shows some error at runtime
1:try use: path = new int [n], rather than path = new int(n);
2:if you want to push elements to graph, you should change your function inp to void inp(vector<vertex>& graph)

Can't copy newly created objects in the Class constructor to its vector member in C++

In the class constructor, I am initializing other objects and pushing these objects to my class vector member. From what I understand, the vector create a copy of the object and stores it so that it doesn't go out of scope. However, when verifying the objects in another class function, they are not initialized anymore. Here's a example code to explain the behaviour:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class Square {
private:
int size_ = 0;
int colour_ = 0;
public:
Square(){
size_ = 0;
colour_ = 0;
}
void init(int size, int colour) {
size_ = size;
colour_ = colour;
}
int get_size() { return size_; }
};
class SetSquares {
private:
std::vector<Square> squares_;
int number_;
public:
SetSquares(): number_(0) {}
void init(int num) {
number_ = num;
squares_.clear();
squares_.resize(num);
for (int i=0; i < num; i++) {
Square square;
square.init(i, i);
squares_.push_back(square);
}
}
void sample(int i) {
if (i >= number_) { return; }
std::cout << "Square size is: " << squares_[i].get_size() << std::endl;
}
};
int main()
{
SetSquares set_of_squares;
set_of_squares.init(7);
set_of_squares.sample(4);
return 0;
}
resize(n) will create n default constructed elements in a vector and push_back will append new elements after those n elements. Use reserve and push_back or resize and index operator as suggested in comment.