I'm trying to call addValues below:
Obj *s = new Obj();
vector<tm> dates(SIZE);
vector<double> values[COUNT];
for (uint i = 0; i < COUNT; i++) {
values[i] = vector<double>(SIZE);
}
s->addValues(&dates, &values); // <- this is the error line
and I've defined addValues:
void addValues(vector<tm> *newDates, vector<double> (*newValues)[COUNT]);
The exact error is:
no matching function for call to ‘Stock::addValues(std::vector<tm, std::allocator<tm> >*, std::vector<double, std::allocator<double> > (*)[5])’
I think the idea is that my method signature does not match.
What is the correct signature for addValues?
template <size_t N>
void addValues(vector<tm>* newDates, vector<double> (&newValues)[N]);
The reason this works is because its a template. The value N is known at compile time since you define values as an array: vector<double> values[COUNT]. Since the compiler knows the size of values at compile time, it is able to replace N with COUNT.
Since it is a template you will be able to call this function with any size array, not necessarily COUNT size.
I would also recommend changing newDates to a reference, as Fred Nurk suggested.
template <size_t N>
void addValues(vector<tm>& newDates, vector<double> (&newValues)[N]);
This is how I rewrote your code to make it compile:
#include <ctime>
#include <vector>
using namespace std;
typedef unsigned int uint;
#define SIZE 3
#define COUNT 3
struct Obj {
void addValues(vector<tm> *newDates, vector<double> (*newValues)[COUNT])
{}
};
int main() {
Obj *s = new Obj();
vector<tm> dates(SIZE);
vector<double> values[COUNT];
for (uint i = 0; i < COUNT; i++) {
values[i] = vector<double>(SIZE);
}
s->addValues(&dates, &values);
}
and it compiles correctly.
As you see, the code is almost the same as yours. Try checking if the COUNT value used in the member function's declaration is the same as the one where you create values.
Related
I am working on my own library and I want to create function max(). I know that function like this exists in C++ and it isn't in namespace std, so erasing using namespace std; won't help. I am creating this function in my namespace like this:
namespace ml
{
template<typename T>T max(T cntr, int size)//I'm getting errors here
{
sort(cntr,0,size-1);//my function which just sorts elements, it's working fine
return cntr[size-1];
}
}
Here is my main function:
#include <iostream>
#include <ctime>
#include "mylib.hpp"
int main()
{
srand(time(NULL));
int* arr, n;
std::cin>>n;
arr = new int [n];
for(int i = 0; i < n; i++)
{
arr[i] = rand()%100;
}
int maximum = ml::max(arr,n);//I'm getting errors here
std::cout<<maximum<<'\n';
return 0;
}
Sorry for grammatical mistakes if i've done so.
If the purpose of the function is to search a C-style array, the signature should be template <typename T> T max(T* cntr, int size). (note the T* as the type of cntr) That way, when it's called with an int*, T is deduced as int, and that's the correct return type.
how do i iterate the pair array arguments passed as a pointer ?
i had tried to use as reference pair &arr . but it doesnt worked either . can i pass pair<lli,lli> a[n]; as reference ??
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#define LOCAL
#include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
typedef long long int lli;
typedef unsigned long long int ulli;
void yeah( pair<lli,lli> *arr ){
// cout << arr[0].ff; 100
//this doesnt work :(
for(auto e : arr){
cout << e.ff << " " << e.ss << endl;
}
}
int main() {
int n = 10;
pair<lli,lli> a[n];
a[0].ff = 100;
a[1].ss = 150;
yeah(a);
}
this is the error im getting
prog.cpp: In function 'void yeah(std::pair)':
prog.cpp:13:18: error: no matching function for call to 'begin(std::pair&)'
for(auto e : arr){
^
^
A possible solution with fixed-size arrays:
template<std::size_t size>
void foo(std::pair<int, int> (&arr)[size]) {
for (auto e : arr) {
...
}
}
constexpr std::size_t n = 10; // should be known at compile time
std::pair<int, int> a[n];
foo(a);
I would recommend ditching the VLA (which is not part of C++ anyway) and use std::vector instead. Include <vector> and change the declaration to this:
std::vector<std::pair<lli, lli>> a(n);
And the function's signature to:
void yeah(std::vector<std::pair<lli, lli>> &arr)
I am trying to loop through a struct array and initialize its member "history", an int array, to 0 (Undoubtedly, you'll have a better suggestion than the one-value-at-a-time loop, which will be welcome, but that's not what the question is about).
I get an error not only I do not understand, but I cannot see how the multiple internet posts about it come into a function within my case.
The error is:
In function 'int main()':....
|error: request for member 'history' in 'coin', which is of non-class type 'coin_t [10]'|
This is my code (true copy-paste from a new project):
#include <iostream>
using namespace std;
// Hand input parameters
const int coinCount=10;
int weight[coinCount]={11,11,9,10,10,10,10,10,10,10};
const int maxDepth=6;
const int caseCount=360;
// GLOBALS
struct coin_t
{
float w;
int history[maxDepth];
int curDepth;
};
coin_t coin[coinCount];
int main()
{
int i,j;
//Initialize coin struct array
for(i=0;i<coinCount;i++)
{
coin[i].w=weight[i];
coin[i].curDepth=-1;
for(j=0;j<maxDepth;j++) coin.history[j]=0; // Here's the error
}
}
coin is an array of struct coin_t with sized coinCount. You need to access by operator[] for the corresponding element in the array.
coin[i].history[j] = 0;
// ^^^
If you want to zero-initialize the history you could do better
struct coin_t
{
float w;
int history[maxDepth]{0};
// ^^^^
int curDepth;
};
by which you can skip the extra looping
for (j = 0; j < maxDepth; j++)
coin[j].history[j] = 0;
That being said C++ offers better std::array. Consider use if its suitable to the case.
im new in c++ (and not to old in programming...) and i have problem with handling vectors and strucs in class.
basically i have a vector and a array of pointers to struct members in the class and i want work on the in my methos but im doing something worng/
here is my movement.h
#pragma once
using namespace std;
class movement
{
private:
static const int MAX_ROW_PER_TRACKER = 100;
static const int MIN_TO_START_CALC = 30;
static const int MAX_TRACKERS = 20;
struct tracker
{
int id;
double a[MAX_ROW_PER_TRACKER];
double b[MAX_ROW_PER_TRACKER];
double c;
};
vector<int> trackersOrder[MAX_TRACKERS] = {};
tracker* trackersArr[MAX_TRACKERS];
public:
movement();
void addRow(int a, int b, int c);
~movement();
};
and my movement.cpp
#include "stdafx.h"
#include "movement.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
movement::movement()
{
}
void movement::addRow(int id, int a, int b)
{
int index;
vector<int>::iterator searchID = find(trackersOrder.begin(), trackersOrder.end(), ID);
if (searchID == trackersOrder.end())
{
vector<int>::iterator freeLocation = find(trackersOrder.begin(), trackersOrder.end(), 0);
index = freeLocation - trackersOrder.begin();
trackersOrder.insert(trackersOrder.begin + index, id);
structArr[index] = new tracker;
structArr[index]->id = id;
structArr[index]->a[0] = a;
structArr[index]->b[0] = b;
structArr[index]->c = 0;
}
}
movement::~movement()
{
}
so when i send to method "addRow" id, and b i want to first check if i allready have this id in my vector (the vector just give me the index for the structs array) and if not then if put the id in the first empty place in the vector and on the structs array/
but from some reasin its look to me that the methid dont reconized the vector and the structs. can you help me understand why?
p.s - i can bet that i have more mistakes in my code, its my firs try with pointers and ect. (im comming from the good life in Matlab) so i will be happy to learn on them also
thank you very much!
The main problem
The problem is that in your code, trackersOrder is not a vector but an array of vectors:
vector<int> trackersOrder[MAX_TRACKERS] = {}; // array of MAXTRACKERS vectors !!
The solution
If you define it as simple vector, it should work better:
vector<int> trackersOrder;
If you want to set its size do it in the movement constructor:
movement::movement() : trackersOrder(MAX_TRACKERS)
{
}
Other issues
There is a case typo with an ID that should be id.
auto searchID = find(trackersOrder.begin(), trackersOrder.end(), id); // by the way auto is easier + ID corrected
There are a missing () after a begin whicn transforms unfortunately your iterator arithmetic into function pointer arithmetic (sic!!):
trackersOrder.insert(trackersOrder.begin() + index, id); // corrected
Finally, there are a couple of structArr that should be replaced by trackersArr.
The result does finally compile (online demo)
in an attempt to understand templates better (and thus be able to read basic documentation on c++), I am trying to perform basic operations on arrays as templates. Below is code that defines a function template for averaging an array:
#include <iostream>
#include <array>
using namespace std;
template<class T>
double GetAverage(T tArray[])
{
T tSum = T(); // tSum = 0
int n=tArray.size();
for (int nIndex = 0; nIndex < n; ++nIndex)
{
tSum += tArray[nIndex];
}
// Whatever type of T is, convert to double
return double(tSum) / n;
}
int main ()
{
array<int,5> data={0,1,2,3,4};
cout << GetAverage(data);
cin.get();
return 0;
}
For some reason, as you will see, the compiler runs into issues when dealing with properties of the array, such as array.size(), all within the defining code of a function. I get the following error:
error: no matching function for call to 'GetAverage'
cout << GetAverage(data);
^~~~~~~~~~
note: candidate template ignored: could not match 'T *' against 'array<int, 5>'
double GetAverage(T tArray[])
^
How can I refer to the properties of an object when defining a function which takes in said object as input (all the while using the language of templates)?
C++11 array is a STL container, not a C array thus the following is incorrect:
T tArray[]
A correct version of the above could be
#include <iostream>
#include <array>
#include <numeric>
using namespace std;
template<class T>
double GetAverage(T tArray)
{
// More compact version as suggested by juanchopanza
auto avg = std::accumulate(begin(tArray), end(tArray), 0.0)/tArray.size();
return avg;
}
int main ()
{
array<int,5> data={0,1,2,3,4};
cout << GetAverage(data);
cin.get();
return 0;
}
http://ideone.com/RyPqOr
if you intend to use something more sophisticated you might have to use a struct or a class since functions don't have partial specialization.