I have read other similar posts but I just don't understand what I've done wrong. I think my declaration of the vectors is correct. I even tried to declare without size but even that isn't working.What is wrong??
My code is:
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
using namespace std;
vector<string> v2(5, "null");
vector< vector<string> > v2d2(20,v2);
class Attribute //attribute and entropy calculation
{
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
public:
Attribute(){}
int total,T,F;
};
int main()
{
Attribute attributes;
return 0;
}
You cannot do this:
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
in a class outside of a method.
You can initialize the data members at the point of declaration, but not with () brackets:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
Before C++11, you need to declare them first, then initialize them e.g in a contructor
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
As an alternative you can use constructor initializer lists
Attribute():name(5), val(5, 0) {}
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}
Related
The vector constructor calls in the statement below construct vectors with 50 elements of identical values in each vector as values in the sviMap. The statement repeats vector<int> three times. Is there a more concise way to achieve this overall initialization of the sviMap where vector<int> appears only once in the statement?
map<string, vector<int>> sviMap { {"Leo", vector<int>(50, 101)} , {"Brad", vector<int>(50, 201)} };
Strictly speaking, no. You need to have template specialization and two instances of the vector.
But if you need to have "this text once", this workaround could work for you:
using vi = vector<int>;
map<string, vi> sviMap{ {"Leo", vi(50, 101)} , {"Brad", vi(50, 201)} };
Formally, this is not "the statement", but two statements, but the vector appears only once. If your goal is to have one point for changes, this could work.
I wanted to correct my mistake, so here's another solution.
And this one will result in vectors of the correct length.
I just used inheritance to create a vector type with a constructor that has the desired behavior, so you can then use initializer lists without extra specifics
#include <cassert>
#include <map>
#include <vector>
#include <string>
template<typename type_t>
class my_vector :
public std::vector<type_t>
{
public:
my_vector() = default;
my_vector(const size_t size, const type_t value) :
std::vector<type_t>(size, value)
{
}
};
int main()
{
std::map<std::string, my_vector<int>> sviMap{ { "Leo", {50, 101}}, { "Brad", {50, 201}} };
auto vec = sviMap["Leo"];
auto value = vec[23];
}
You can do it like this, just use nested initializers
#include <map>
#include <vector>
#include <string>
int main()
{
std::map<std::string, std::vector<int>> sviMap
{
{"Leo", {50, 101}},
{"Brad", {50, 201}}
};
auto vec = sviMap["Leo"];
}
I need to build a vector of a class that can have multiple type like this:
#include <variant>
#include <vector>
#include "Field.h"
using namespace std;
int main()
{
variant <int, float> v;
vector <variant<Field<int>, Field<string>, Field<float>>> fdList;
fdList[0].getName();
}
And this is header file Field.h:
#pragma once
#include <string>
#include <vector>
using namespace std;
template<class T>
class Field
{
public:
Field();
Field(string);
void setName(string);
string getName();
bool isPrime();
void toPrime();
void toForeign(Field);
~Field();
private:
string FD_Name;
vector <T> records;
bool isPrimeK = false;
string message;
};
template<class T>
string Field<T>::getName()
{
return FD_Name;
}
When I try to access getName() function, Visual Studio keeps giving me the following message error:
E0135 class "std::variant<Field, Fieldstd::string, Field>" has no member "getName"
C2039 'getName': is not a member of 'std::variant<Field,Fieldstd::string,Field>'
But it works just fine, if I define my vector like this:
vector <Field<int>> fdList;
fdList[0].getName();
How can I fix this?
For any issue about standard library, I recommend you to check document first.
You can see here about how to use std::variant.
In short, you cannot access the content in your std::variant like that because its type is std::variant but not the types you store in it. For your case, I think you may want to check what's inside first by calling std::variant::index() method, then get the value by calling std::get.
Calling a method on variant doesn't automatically call the method of the active alternative of variant. You'll have to visit the active alternative and invoke the corresponding handler. In your case, since you want to handle all of the potential active alternatives the same way, you can do:
std::visit([](const auto& field) {
field.getName();
// ...
}, fdList[0]);
Alternatively, you can wrap the variant in something like:
struct AnyField {
string getName() const {
return std::visit([](const auto& field) { return field.getName(); }, v);
}
std::variant<Field<int>, Field<string>, Field<float>> v;
};
then use them like you wanted to:
vector<AnyField> fdList;
fdList[0].getName();
I have a problem with vector declaration and initialization in a
class constructor. I have a Station.h and Station.cpp files of a class and I recall it in main :
Station.h
#ifndef STATION_H
#define STATION_H
#include <vector>
class Station
{
public:
int num_bin;
int num_staz;
vector<int> binari; //here already gives me error! Vector does not name a type
Station(int num_staz, int num_bin);
virtual ~Station();
Station(const Station& other);
protected:
private:
};
Then I want to initialize the vector in the constructor of .cpp like that:
Station.cpp
#include "Station.h"
using namespace std;
Station::Station(int num_staz, int num_bin)
{
this->num_bin = num_bin;
this->num_staz = num_staz;
this->binari(num_bin); //here I want to create a vector of num_bin size
}
and then call it in main like that:
main.cpp
#include <iostream>
#include "Station.h"
using namespace std;
int main()
{
Station staz1(2,3);
staz1.binari.push_back(300); // error! class Station has no member binari
staz1.binari.push_back(250);
staz1.binari.push_back(150);
return 0;
}
Where am I making a mistake?
this->binari(num_bin); //here I want to create a vector of num_bin size
The function you need to use is std::vector::resize().
this->binari.resize(num_bin);
It will be better to initialize the object with the appropriate size as:
Station::Station(int num_staz, int num_bin) : num_bin(num_bin),
num_staz(num_staz),
binari(num_bin)
{
}
this->binari(num_bin); This doesn't work because it is not an initialization that is why it doesn't work.
To make this work use it in in-class initialization list:
Station::Station(int num_staz, int num_bin) :
num_bin(num_bin),
num_staz(num_staz),
binari(num_bin)
{
}
I could not declare an array of strings in my class. Below my class definition:
class myclass{
public:
int ima,imb,imc;
string luci_semaf[2]={"Rosso","Giallo","Verde"};
};
and my main file
#include <iostream>
#include <fstream>
#include "string.h"
#include <string>
using namespace std;
#include "mylib.h"
int main() {
return 0;
}
Why do I get the following warnings / error?
You have two problems: The first is that you can't initialize the array inline like that, you have to use a constructor initializer list. The second problem is that you attempt to initialize an array of two elements with three elements.
To initialize it do e.g.
class myclass{
public:
int ima,imb,imc;
std::array<std::string, 3> luci_semaf;
// Without C++11 support needed for `std::array`, use
// std::string luci_semaf[3];
// If the size might change during runtime use `std::vector` instead
myclass()
: ima(0), imb(0), imc(0), luci_semaf{{"Rosso","Giallo","Verde"}}
{}
};
You can not initialize data member.
You can write like this:
class myclass{
public:
myclass() {
luci_semaf[0] = "Rosso";
luci_semaf[1] = "Giallo";
luci_semaf[2] = "Verde";
}
private:
int ima,imb,imc;
string luci_semaf[3];
};
You can assign the values of the array in the Сonstructor
You're declaring an array of size 2 but providing 3 strings!
Try storing the elements in vector of strings, in c++ vectors are used more often.
class myclass{
public:
int ima,imb,imc;
std::vector<std::string> strings;
myclass() {
strings.push_back("blabla");
}
};
I'm trying to create a vector with a specific size, of 255 (max)..
It doesnt work for me, like I see in examples over the internet...
I'm using Microsoft Visual C++ 2012...
I have the current code :
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;
const int MAX = 255;
class test
{
vector <string> Name(MAX);
};
int main()
{
system("PAUSE");
}
It gives me 2 errors :
Error 1 error C2061: syntax error : identifier 'MAX'
2 IntelliSense: variable "MAX" is not a type name
Thanks for your help!
That's not valid syntax for a class declaration. Try:
class test
{
vector <string> Name;
test() : Name(MAX) {}
};
You can write vector <string> Name(MAX); when you create a variable (in your case, you're declaring a member). For example:
int main()
{
vector <string> Name(MAX);
}
would be perfectly valid.
You can't pass arguments to the std::vector constructor int the class declaration. You should put that in the constructor for your class, like this, which utilizes does it via an initializer list:
class test
{
std::vector<std::string> Name;
public:
test():
Name(MAX)
{
}
};
You cannot initialize a data member inside the class declaration like this. Use the member initialization list in your constructor of the class to initialize vector<string> Name.
test::test
:Name(MAX)
{
//
}
Your main would be like this.
test t1 ;
It would automatically call the constructor and all the fields of t1 would be created, including vector<string> Name.