在包含多个变量的自定义数据类型的矢量模板中访问变量 [英] Accessing variables in a template that is a vector of a custom data type with multiple variables
问题描述
如何在增量$内访问变量
itemtype
和 total
c $ c>函数?我在下面的代码给我错误,如下所示:
Counter2.h:在成员函数'int Counter :: increment(T)'中:
Counter2.h:28:31:error:'itemtype'未在此范围内声明
Counter2.h:36:22:错误:'itemtype'未在此范围内声明
Counter2.h:36:39:错误:'total'未在此范围内声明
我必须能够使用命令计数器< T> counter;
其中T可以是任何类型,如字符串和 counter.increment()
#包括<串GT;
//#include< cstdlib>
#include< vector>
使用std :: vector;
使用std :: string;
模板< class T>
类记录{
public:
T itemtype;
int total;
};
模板< class T>
class Counter {
vector<记录和LT; T> >数据;
public:
int increment(T item);
int count(T item);
void printSummary();
};
模板< class T>
int Counter< T> :: increment(T item){
bool check = false;
$ b $ for(int i = 0; i< data.size(itemtype); i ++){
if(data [i] .itemtype == item){
data [I]。总++;
bool check = true;
休息;
if(check == false){
data.push_back(itemtype = item,total = 1);
int main(){
计数器< string>计数器;
counter.increment(orange);
counter.increment(orange);
返回0;
c> for(int i = 0; i< data.size(itemtype); i ++){
将会是: $ b
)和 0; i< data.size(); i ++){
> data.push_back(itemtype = item,total = 1); 可以是:
$ b
-
data.push_back({item,1}); //通过使用初始化器列表; C ++ 11
-
或者,
Record r;
r.itemtype = item;
r.total = 1;
data.push_back(r);
你可以看看: http://www.cplusplus.com/reference/vector/vector/
知道关于std :: vector。
How do I access the variables itemtype
and total
within the increment
function? The code I have below gives me errors as follows
Counter2.h: In member function ‘int Counter::increment(T)’:
Counter2.h:28:31: error: ‘itemtype’ was not declared in this scope
Counter2.h:36:22: error: ‘itemtype’ was not declared in this scope
Counter2.h:36:39: error: ‘total’ was not declared in this scope
I must be able to use the command Counter<T> counter;
where T can be any type, such as string and counter.increment()
#include<string>
//#include<cstdlib>
#include<vector>
using std::vector;
using std::string;
template<class T>
class Record{
public:
T itemtype;
int total;
};
template<class T>
class Counter{
vector< Record<T> > data;
public:
int increment(T item);
int count(T item);
void printSummary();
};
template<class T>
int Counter <T> :: increment(T item){
bool check = false;
for(int i=0; i < data.size(itemtype); i++){
if(data[i].itemtype == item){
data[i].total++;
bool check = true;
break;
}
}
if(check == false){
data.push_back(itemtype = item, total = 1);
}
}
int main(){
Counter<string> counter;
counter.increment("orange");
counter.increment("orange");
return 0;
}
In line for(int i=0; i < data.size(itemtype); i++){
will be: for(int i=0; i < data.size(); i++){
And data.push_back(itemtype = item, total = 1);
can be:
data.push_back({item, 1}); // by using initializer list ; C++11
or,
Record r; r.itemtype = item; r.total = 1; data.push_back(r);
You can look at : http://www.cplusplus.com/reference/vector/vector/ to know about std::vector.
这篇关于在包含多个变量的自定义数据类型的矢量模板中访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!