A very basic question, but i haven't found the answer yet.
I wrote an Application which is using an Array with a constant predefined Value which defines the size of this array. So but now i want to change this so that the "list" can theoretically be endless (i know that it would be practically impossible). For that I want to use a vector. But when I type the following it gives me an Error:
edit(2): Wrote accidentially const and a wrong parameter for push_back funktion, heres the final version, which gives the error.
#include "stdafx.h"
#include "string"
#include "vector"
using namespace std;
struct Board {
vector <string> myVector;
myVector.push_back("foo");
};
Error Message:
<error-type> Board::myVector
This declaration has no storage class or type specifier.
My thought was that vectors dont work in structs. I heard that structs are a plain C thing and vectors are more a C++ thing, maybe thats why it is so? But actually I have no clue, thats why I am asking here :)
edit (1):
I just gave you the visual studio error, maybe I should give you the compiler errors..:
error C3927: '->': trailing return type is not allowed after a non-function declarator
error C3484: syntax error: expected '->' before the return type
error C3613: missing return type after '->' ('int' assumed)
error C3646: 'push_back': unknown override specifier
error C2059: syntax error: '('
error C2238: unexpected token(s) preceding ';'
The problem are as followings:
(corrected in OP question) myVector is defined const
myVector.push_back(1); is not in any function body.
(corrected in OP question) Value passed to myVector.push_back(1); is int but vector is of type string
Change it as following. See example program working here:
#include "string"
#include "vector"
#include "iostream"
using namespace std;
struct Board {
vector<string> myVector;
void push_back(string val)
{
myVector.push_back(val);
}
void print()
{
for (auto it = myVector.begin(); it != myVector.end(); ++it)
cout << " | " << *it;
}
};
int main()
{
Board b;
b.push_back("Value 1");
b.push_back("Value 2");
b.print();
return 0;
}
UPDATE:
(can you actually use push_back for a vector in a struct without creating an extra function?)
No. structure can have only data members and member functions. but you can use initializer-list to initialize vector as following:
vector<string> myVector{"IVal 1", "IVal 1"};
If you wants to put the initlize value always at the end then use vector.insert() instead of vector.push_back().
Related
I am trying to pass a string to a function, which is going to be sorted. Then to have the sorted string to be return from it. It won't compile, and it even says that "binarySort is not a member of Others".
Is it something that's not allowed to do?
This is the Class File
#include "Others.h"
#include <iostream>
using namespace std;
char Others::inputCheck(char guess) {
while (!isalpha(guess)) { //If the inputs are not alphabets, keep looping.
cout << "Enter again: ";
cin >> guess;
}
cin.ignore(1, '\n');
guess = tolower(guess);
return guess;
}
string Others::binarySort(string sampleText) {
//Bubble sorting the string. (Copy pasted)
for (int i = 0; i < sampleText.length(); i++)
{
for (int j = i + 1; j < sampleText.length(); j++)
{
if (sampleText[i] > sampleText[j]) //if previous has bigger ascii value than next,
{
//swapping the prev and next characters
char temp = sampleText[i];
sampleText[i] = sampleText[j];
sampleText[j] = temp;
}
}
}
return sampleText;
}
This is the Header File.
#ifndef OTHERS_HEADER
#define OTHERS_HEADER
#pragma once
class Others
{
public:
char inputCheck(char guess); //Function to check if inputs are alphabets.
string binarySort(string sampleText);
};
#endif
The main function.
#include <iostream>
#include "Others.h"
using namespace std;
int main() {
string sortedText, sampleText = "toibeawn";
Others sorter;
sortedText = sorter.binarySort(sampleText);
cout << "Text after sorted:\n";
cout << sortedText;
return 0;
}
The sort works if it's not used for a function.
The error output:
1>Sorting_test.cpp
1>Others.cpp
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\Others.h(9,7): error C2039: 'string': is not a member of 'std'
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\predefined C++ types (compiler internal)(368): message : see declaration of 'std'
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\Others.h(9,24): error C3646: 'binarySort': unknown override specifier
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\Others.h(9,24): error C2059: syntax error: '('
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\Others.h(9,30): error C2039: 'string': is not a member of 'std'
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\predefined C++ types (compiler internal)(368): message : see declaration of 'std'
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\Others.h(9,48): error C2238: unexpected token(s) preceding ';'
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\Others.cpp(16,21): error C2039: 'binarySort': is not a member of 'Others'
1>C:\Users\yap_2\source\repos\Sorting\Sorting_test\Others.h(5): message : see declaration of 'Others'
1>Generating Code...
1>Done building project "Sorting_test.vcxproj" -- FAILED.
You include "Others.h" prior to declaring using namespace std which results in string being unrecognized in the included header.
Add using namespace std; in the header "Others.h" and the error will be gone.
Generally, it is a bad practice to have using namespace std in headers and you'd better just write std::string.
Everything is fine. Require changes a simple change.
in your header include this header : #include and use std namespace.
So after changes, your header looks like
#ifndef OTHERS_HEADER
#define OTHERS_HEADER
#pragma once
#include <iostream>
using namespace std;
The main problem is, in your header the string is not resolved due to the lake of string header and std namespace.
Note: Always try to include language headers first and then your custom headers.
std::string binarySort(std::string sampleText)
Needed a namespace
Ive looked all over and I cant find anything relating to my problem. Im trying to write a class definition for a polygon class that basicly has a vector that holds pointers to a point. When I try to compile i keep geting the folllowing errors...
error C2143: syntax error : missing ';' before '<'
error C4430: missing type specifier - int assumed.
error C2238: unexpected token(s) preceding ';'
error C2061: syntax error : identifier 'vector'
error C2065: 'myPolygonPoints' : undeclared identifier
error C2065: 'points' : undeclared identifier
error C2065: 'myHasInstersection' : undeclared identifier
error C2660: 'Polygon::addSetOfPoints' : function does not take 1 arguments
Here is the code to the class
#include "Point.h"
#include <vector>
class Point;
class Polygon
{
private:
vector<Point*> myPolygonPoints;
bool myHasIntersection;
public:
void addSetOfPoints(vector<Point*> points)
{
myPolygonPoints = points;
}
bool getHasIntersection()
{
return myHasIntersection;
}
void setHasIntersection(bool intersection)
{
myHasInstersection = intersection;
}
};
You are using vector from the std namespace without qualifying it.
You either have to do using namespace std;, or using std::vector, or declaring all your vector objects with the std namespace like std::vector.
#include "Point.h"
#include <vector>
class Point; // Assuming Point.h has this declared,
// you don't need this forward declaration, but in reality,
// you don't need to include Point.h
// since you're only declaring pointers to Points
class Polygon
{
private:
std::vector<Point*> myPolygonPoints;
bool myHasIntersection;
public:
void addSetOfPoints(std::vector<Point*> points)
{
myPolygonPoints = points;
}
bool getHasIntersection()
{
return myHasIntersection;
}
void setHasIntersection(bool intersection)
{
myHasInstersection = intersection;
}
};
vector is in the std:: namespace. so vector is undefined in your example code
Two possible solutions:
#include <vector>
using std::vector;
or: (in all cases through the code where you reference vector, both declaration and reference)
private:
std::vector<Point*> myPolygonPoints;
public:
void addSetOfPoints(std::vector<Point*> points)
etc.
A third solution is the following:
#include <vector>
using namespace std;
This last one, from a coding style perspective, I find less preferred. The reason is that it imports absolutely everything in the std namespace into the default namespace. By contrast, I find it preferrable to explicitly import the pieces I'm using, becuase it allows me to keep track of why I need a header. This doesn't make a sense in this case (of course I need <Vector>, I'm using std::vectors). It's much more relevant in a case like this:
#include <algorithm>
using std::adjacent_find;
Oh yeah, that's why I included that...
If you're not explicitly declaring that you're using the std namespace you should reference which namespace vector belongs to.
Besides the std::vector problem, you have also mispelled the myHasIntersection variable in the setHasIntersection method.
now what is wrong with this code!
Header:
#pragma once
#include <string>
using namespace std;
class Menu
{
public:
Menu(string []);
~Menu(void);
};
Implementation:
#include "Menu.h"
string _choices[];
Menu::Menu(string items[])
{
_choices = items;
}
Menu::~Menu(void)
{
}
compiler is complaining:
error C2440: '=' : cannot convert from 'std::string []' to 'std::string []'
There are no conversions to array types, although there are conversions to references or pointers to arrays
there is no conversion! so what is it on about?
please help, just need to pass a bloody array of strings and set it to Menu class _choices[] attribute.
thanks
Array's cannot be assigned, and your arrays have no sizes anyway. You probably just want a std::vector: std::vector<std::string>. This is a dynamic array of strings, and can be assigned just fine.
// Menu.h
#include <string>
#include <vector>
// **Never** use `using namespace` in a header,
// and rarely in a source file.
class Menu
{
public:
Menu(const std::vector<std::string>& items); // pass by const-reference
// do not define and implement an empty
// destructor, let the compiler do it
};
// Menu.cpp
#include "Menu.h"
// what's with the global? should this be a member?
std::vector<std::string> _choices;
Menu::Menu(const std::vector<std::string>& items)
{
_choices = items; // copies each element
}
You can't define the array as string _choices[], that defines an array with unknown size, which is illegal.
If you change it to string * _choices it will work just fine (though be aware it will only copy a pointer to the array, and not clone it all).
Also, don't you want _choices to be a field of the class, instead of a global?
I'm stuck! I have this very simple test code and I can't get it to compile! I have used the same code many times before but now it won't work!
I have this simple program
#include <vector>
#include <iostream>
#include "Rswap.h"
using namespace std;
int main(){
Rswap test();
cin.get();
return 0;}
And then the rswap.cpp...
#include <vector>
#include "Rswap.h"
Rswap::Rswap(){
V.push_back(9);
};
And then the rswap.h...
#ifndef Rswap_h
#define Rswap_h
class Rswap{
public:
vector<int>V;
Rswap();
};
#endif
I'm using Visual studio 2008. Is there something wrong that is obvious and I'm missing or what could it be! As I said I have used this snippet on several differnet occassions and I can't find any difference between this and those that work...
And i have tried both
vector < int > V; and vector <int> V; without any luck
I have stared at this blindly now for some while so I thought it's better to ask here!
rswap.h(7) : error C2143: syntax error : missing ';' before '<'
rswap.h(7) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
rswap.h(7) : error C2238: unexpected token(s) preceding ';'
At the point you #include "Rswap.h", you haven't declared using namespace std; yet, so the reference to vector in Rswap.h must be qualified with a namespace. Simply declare the vector with a namespace prefix.
class Rswap{
public:
std::vector<int>V;
Rswap();
};
Also, I suggest you #include <vector> from Rswap.h rather than relying on whoever uses Rswap.h to get the #include order right.
It should be
std::vector<int>V;
Ah, your using namespace std comes too late - it should be inserted BEFORE the rswap.h include. In any case, it's MUCH better to write std::vector instead.
You need to #include <vector> in rswap.h.
I am trying to combine using a std::set and a class, like this:
#include <set>
class cmdline
{
public:
cmdline();
~cmdline();
private:
set<int> flags; // this is line 14
};
but, it doesn't like the set flags; part:
cmdline.hpp:14: error: ISO C++ forbids declaration of 'set' with no type
cmdline.hpp:14: error: expected ';' before '<' token
make: *** [cmdline.o] Error 1
As far as I can see, I gave a type (of int). Do you write the "set variable" line differently, or is it not allowed there?
You need to use std::set; set is in the std namespace.
You mean std::set.
You have to use the std:: namespace (for all STL/SL classes).
std::set< int > myset;
or
using namespace std; // don't do this in a header - prefer using this in a function code only if necessary