I am having trouble with my void print function to print out this vector. I'm not quite sure what it is talking about with "std::allocator. I get these errors:
st1.cpp: In function ‘void Print(std::vector<int, std::allocator<int> >)’:
st1.cpp:51: error: declaration of ‘std::vector<int, std::allocator<int> > v’ shadows a parameter
Here is the file:
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
void Initialize();
void Print();
int main()
{
stack<string> s1, s2;
s1.push("b");
s2.push("a");
if (s1.top() == s2.top())
{
cout << "s1 == s2" << endl;
}
else if (s1.top() < s2.top())
{
cout << "s1 < s2" << endl;
}
else if (s2.top() < s1.top())
{
cout << "s2 < s1" << endl;
}
else
{
return 0;
}
vector<int> v;
Initialize();
Print();
}
void Initialize(vector<int> v)
{
int input;
cout << "Enter your numbers to be evaluated: " << endl;
while(input != -1){
cin >> input;
v.push_back(input);
//write_vector(v);
}
}
void Print (vector<int> v){
vector<int> v;
for (int i=0; i<v.size();i++){
cout << v[i] << endl;
}
}
I just want to print v out to the screen. Any help?
Your function declaration and definition are not consistent, you want to generate vector from Initialize, you can do:
void Initialize(vector<int>& v);
To print vector:
void Print(const vector<int>& v);
Now you call:
vector<int> v;
Initialize(v);
Print(v);
Don't forget to change function definition of Initialize, Print to match the new signature I provided above.
Also you are redefining a local variable v which shadows function parameter, you just need to comment out that line, also pass vector by const ref:
void Print (const vector<int>& v){
//vector<int> v;
for (int i=0; i<v.size();i++){
cout << v[i] << endl;
}
}
You have to pass by const reference and remove the extraneous vector.
void Print(const std::vector<int>& v){
for(unsigned i = 0; i< v.size(); ++i) {
std::cout << v[i] << std::endl;
}
}
Another way to print it out would be to use iterators like so:
void Print(const std::vector<int>& v) {
std::vector<int>::iterator it;
for(it = v.begin(); it != v.end(); ++it) {
std::cout << (*it) << '\n';
}
}
Or in C++11 you can do it like so:
void Print(const std::vector<int>& v) {
for(auto& i : v)
std::cout << i << '\n';
}
I don't think your Initialize() function works like you expect it to. It seems to just make a copy and then discards it, not modifying any values of the existing vector.
Leveraging c++ std's 11 onwards, this could be acheived in one line as shown below.
std::for_each(v.begin(),v.end(),[](const int &i) { std::cout << i; });
This code runs a for loop using std::vector iterators from begin() to end(), serially feeding the lambda/[] function the required argument to be printed.
Related
I have such a code
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void removeFirstFromVec(vector<int> & vecLink) {
// remore first element from some vector
vecLink.erase(vecLink.begin() + 0);
}
int main()
{
vector<int> myVec;
myVec.push_back(1);
myVec.push_back(2);
myVec.push_back(3);
cout << "Before removal\n";
for (auto & i : myVec) {
cout << myVec[i-1] << endl;
}
removeFirstFromVec(myVec);
cout << "After removal\n";
for (auto & i : myVec) { // starts with 2
cout << myVec[i-1] << endl;
}
return 0;
}
But on the place where I put a comment it starts with 2 instead of 0 and it causes an error. What I've done wrong or is there a way to use something brief like auto & i : myVec instead of for (int i = 0; i < ...size(); i++) without such an error
In the range-based for loop
for (auto & i : myVec) {
cout << myVec[i-1] << endl;
}
i is the element of the vector, not the index. It should be
for (auto & i : myVec) {
cout << i << endl;
}
Iteration returns the items themselves, not indices.
vector<int> vec { 5, 3, 2 };
for (int i: vec) {
cout << i << endl;
}
Will output this:
5
3
2
If you do the following:
Use templated-function to accept any type for the vector.
Use direct initialization method rather than push_back() to avoid huge number of lines.
Braces for single syntax is optional. Avoid it to reduce confusion during coding complex programs.
Then you can write the same code in a better manner (don't forget the comments):
#include <iostream>
#include <vector>
using namespace std;
// defining a templated-function
template<class T>
void removeFirstFromVec(vector<T>& vecLink) {
vecLink.erase(vecLink.begin());
}
int main(void) {
// initializing with direct-initialization method
vector<int> myVec {1, 2, 3};
cout << "Before removal\n";
// no braces
for (auto& i : myVec)
// 'i' isn't an index here, it's an element
cout << i << endl;
removeFirstFromVec(myVec);
cout << "After removal\n";
// no braces
for (auto& i : myVec)
cout << i << endl;
return 0;
}
The bubblesort() function I have for my vector, fails to return a sorted version of the vector; there are times where if I do compile and execute the code in VS it gives me a runtime error when the function is called:
Expression: vector subscript out of range
I've double checked the range, and it seems alright to me; I'm unsure what the issue is: I did make sure the vector was passed by reference.
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
template <class T>
void fillVector(std::vector<T>& vobj, int n);
template <class T>
void displayVector(std::vector<T>& vobj);
template <class T>
void bubbleSort(std::vector<T>& vobj);
template <class T>
void fillVector(std::vector<T>& vobj, int n)
{
srand((unsigned int)time(NULL));
for (int i=0; i<n; ++i)
{
vobj.push_back(rand());
}
}
template <class T>
void displayVector(std::vector<T>& vobj)
{
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
for (unsigned i=0; i<displayLimit; ++i)
{
std::cout << " " << vobj[i];
}
std::cout << " ..." << std::endl;
}
else
{
for (unsigned i = 0; i < vobj.size(); ++i)
{
std::cout << vobj[i] << " ";
}
}
}
template <class T>
void bubbleSort(std::vector<T>& vobj)
{
bool swapped = true;
for (unsigned i=0; swapped && i<vobj.size()-1; ++i)
{
swapped = false;
for (unsigned j=0; j<vobj.size()-1-i; ++j)
{
if (vobj[j]>vobj[j++])
{
swapped = true;
std::swap(vobj[j],vobj[j++]);
}
}
}
}
int main()
{
std::vector<int> vobj;
std::cout << "Enter # of objects you'd like to store in the vector object: ";
int n;
std::cin >> n;
std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
fillVector(vobj,n);
std::cout << "\n*** Calling displayVector(...) ***" << std::endl;
std::cout << "Vector object contains " << n << " value(s) which are" << std::endl;
displayVector(vobj);
std::cout << "\n*** Calling bubbleSort(...) ***" << std::endl;
bubbleSort(vobj);
displayVector(vobj);
}
In your bubbleSort routine you increment the j variable 3 times! Don't you think that is twice too many?
if (vobj[j]>vobj[j++])
should be
if (vobj[j]>vobj[j+1])
and
std::swap(vobj[j],vobj[j++]);
should be
std::swap(vobj[j],vobj[j+1]);
Incrementing a variable is not the same as adding one to it.
I am trying to figure out how to bubble sort a 2D string array. I am currently stuck trying to figure out why my program isnt sorting the strings. I spsupect it could be possible that something is wrong with void swap. I feel somehting with the 2D array needs to be put in there. I am not very sure I just learned how to create bubble sorting algorithms.
#include
using namespace std;
const int SIZE = 2;
const int ROWS = 2;
void bubbleSort(string values[][SIZE]);
void swap(int &, int &);
int main ()
{
string values[ROWS][SIZE] = {{"A23", "A12"}, {"name1", "name2"}};
cout << "Unsorted Values: " << endl;
for(auto element : values)
cout << element << " ";
cout << endl;
cout << "Sorted Values" << endl;
bubbleSort(values);
for (auto element:values)
cout << element << " ";
return 0;
}
void bubbleSort(string values[][SIZE])
{
int maxElement;
int index;
for (maxElement = SIZE - 1; maxElement > 0; maxElement--)
{
for( index = 0; index < maxElement; index++)
{
if (values[0][index] > values[0][index + 1])
{
swap(values[0][index], values[0][index + 1]);
}
}
}
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
Your program prints out the adresses because your print loop iterate each entry of your string 2D array. Consequently, every entry is an array. So arr holds the pointer to the first element of the array.
You only need a nested loop to print out the values of the single elements:
for (auto row : values)
for (int i = 0; i < SIZE; i++)
std::cout << row[i] << " ";
Furthermore, there is no need to implement an own swap function. Just use std::swap(T&,T&)
But i assume that you want to achieve a multi array sort. Then you should use a simple struct to represent an entity instead of multiple arrays and implement a operator to compare two entities. I suggest to use a range based container too. Then you can take advantage of the standard sort functions.
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Entry
{
string id;
string name;
bool operator<(const Entry& comp)
{
return id < comp.id;
}
};
int main()
{
auto print = [](const vector<Entry>& vec)
{
for (auto& el : vec)
{
cout << el.id << "->" << el.name << "\t";
}
};
vector<Entry> values { {"A23","name1" }, {"A12", "name2"} };
cout << "Unsorted Values: " << endl;
print(values);
cout << endl;
std::sort(values.begin(), values.end());
cout << "Sorted Values" << endl;
print(values);
return 0;
}
Prints out:
Unsorted Values:
A23->name1 A12->name2
Sorted Values:
A12->name2 A23->name1
I am the beginner of C++, and any help will be very appreciated.
here is the code i can run successfully:
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
main(){
bool findIn=false;
RowVectorXd A(10);
A<<false,true,false,true,true,false,false,false,true,true;
std::cout << A << std::endl;
for (int i=0;i<A.size();i++){
if(A(i)==findIn){
std::cout << i << std::endl;
}
}
system("pause");
}
the result is {0,2,5,6,7}, and I want to design a function, the code is as follows:
int seq(bool findIn, VectorXd &resdX){
VectorXd A;
for(int i=0;i<resdX.size();i++){
if(resdX(i)==findIn){
A =A+i;
}
}
return(A);
}
I want this function to return result like that {0,2,5,6,7}.But I don`t know how to set up a array to save the result or is there a function just like 'which' in R software to produce sequence above.
Sounds like you want a vector of integers:
#include <vector>
std::vector<int> seq(bool findIn, VectorXd &resdX)
{
std::vector<int> v;
for(int i=0;i<resdX.size();i++) {
if (resdX(i) == findIn) {
v.push_back(i);
}
}
return v;
}
You can then print its contents by iterating through it:
std::vector<int> result = seq(false, A);
for (int i : result) std::cout << i << '\n';
I did not understand what are you looking for.
If you want just to print a sequence of integers indexing findIn values you might code:
void seq(bool findIn, VectorXd &resdX) { // not int
std::cout << "{ ";
for(int i=0;i<resdX.size();i++) // go inside the array
if(resdX(i)==findIn) // if you find that resdX(i) value equals findIn value
std::cout << i << " "; // print i index
std::cout << "}" << std::endl; // at the end prints a new line
}
EDIT1:
Try to adapt the following snippet:
#include <list>
...
std::list<int> seq(bool findIn, VectorXd& resdX) {
std::list<int> l;
for(int i=0; i<resdX.size(); i++) {
if (resdX(i) == findIn) {
l.push_back(i);
}
}
return l;
}
void print_seq(std::list<int> list_) {
std::cout << "{ ";
std::list<int>::iterator it = list_.begin();
for (; it != list_.end(); ++it) {
std::cout << i << " ";
}
std::cout << " }\n";
}
I am making some testing of vectors arrays and I don't know how to print it.
Here is my code:
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include "vector"
#include <windows.h>
using namespace std;
vector<vector<int>> generateArrays(){
vector<vector<int>> cisla;
for(unsigned int i=1; i < 11; i++){
vector<int> pole;
vector<int> pole2;
for(unsigned int j=0; j < i*5; j++){
int a = rand();
pole.push_back(a);
pole2.push_back(a);
}
cisla.push_back(pole);
cisla.push_back(pole2);
}
return cisla;
}
vector<vector<int>> arrays = generateArrays();
void Print (const vector<int>& arrays){
// function for prinitng arrays
}
int main(){
Print(arrays);
system("pause");
}
What I need is some function to write down all numbers in vector arrays. I tried to Google it but none of the code work for me.
// requires #include <algorithm> for std::copy
// requires #include <iterator> for std::ostream_iterator
void Print(const vector<vector<int>>& arrays, std::ostream& out = std::cout)
{
for(const auto& array:arrays) {
std::copy(array.begin(), array.end(), std::ostream_iterator<int>(out, " "));
out << std::endl;
}
}
You can use vector::iterator, for instance:
vector<vector<int>>::iterator i = arrays.begin();
vector<int>::iterator j = *i.begin();
for(;i != arrays.end(); ++i) {
for(;j != *i.end(); ++j) {
std::cout << *j << " ";
}
std::cout << "\n";
}
void Print (const vector<int>& arrays){
for (std::vector<int>::iterator it = arrays.begin() ;
it != arrays.end();
++it)
std::cout << ' ' << *it;
}
#include <algorithm>
vector<vector<int>>::iterator it = arrays.begin();
while ( !(it == arrays.end()) {
std::copy( (*it).begin(), (*it).end(),
std::ostream_iterator<int>( std::cout, ","));
++it;
}
As you have std::vector<std::vector<int>> then the function could look as
void Print( const std::vector<std::vector<int>> &arrays )
{
for ( const std::vector<int> &v : arrays )
{
for ( int x : v ) std::cout << x << ' '; // you can include std::setw here
std::cout << std::endl;
}
}
Or if you need to output only std::vector<int> then it will look as
void Print( const std::vector<int> &arrays )
{
for ( int x : arrays ) std::cout << x << ' '; // you can include std::setw here
}
If your compiler does not support the range based for statement then you can use for example standard algorithm std::copy.
void Print( const std::vector<int> &arrays )
{
std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, " " ) );
}
Or you can use an ordinary loop
void Print( const std::vector<int> &arrays )
{
for ( std::vector<int>::size_type i = 0; i < arrays.size(); i++ )
{
std::cout << arrays[i] << ' '; // you can include std::setw here
}
}
Or with iterators
void Print( const std::vector<int> &arrays )
{
for ( auto it = arrays.begin(); it != arrays.end(); ++it )
{
std::cout << *it << ' '; // you can include std::setw here
}
}
What about this?
Create a stream output operator for vector of T like this:
template <typename T>
std::ostream& operator<<(std::ostream& os, std::vector<T> const & array)
bool seenFirst = false;
os << "[ ";
for (auto const & i : array)
{
if (!seenFirst)
{
seenFirst = true;
os << i;
}
else
{
os << ", " << i;
}
}
os << "]";
return os;
}
At the end you might use it for std::vector<int> as well as for std::vector< std::vector <int> > like this:
std::cout << arrays;
If you have Print prototype as shown
then,
void Print (const vector<int>& arrays){
for(auto x:arrays)
std::cout << x <<" ";
}
int main(){
for(const auto& array:arrays)
Print(array);
system("pause");
}
Otherwise you can combine both in one function like
void Print (const vector<vector<int>>& arrays){
for(const auto& array:arrays)
for(auto x:array)
std::cout << x <<" ";
}
In C++11``
for (auto i = path.begin(); i != path.end(); ++i)
std::cout << *i << ' ';
for(int i=0; i<path.size(); ++i)
std::cout << path[i] << ' ';