C++ for loop on 2d array - c++

This is my 2d array:
int pay_scale[15][10] =
{ { 18526, 19146, 19762, 20375, 20991, 21351, 21960, 22575, 22599, 23171},
{ 20829, 21325, 22015, 22599, 22853, 23525, 24197, 24869, 25541, 26213 },
{ 22727, 23485, 24243, 25001, 25759, 26517, 27275, 28033, 28791, 29549},
{ 25514, 26364, 27214, 28064, 28914, 29764, 30614, 31464, 32314, 33164},
{ 28545, 29497, 30449, 31401, 32353, 33305, 34257, 35209, 36161, 37113},
{ 31819, 32880, 33941, 35002, 36063, 37124, 38185, 39246, 40307, 41368},
{ 35359, 36538, 37717, 38896, 40075, 41254, 42433, 43612, 44791, 45970},
{ 39159, 40464, 41769, 43074, 44379, 45684, 46989, 48294, 49599, 50904},
{ 43251, 44693, 46135, 47577, 49019, 50461, 51903, 53345, 54787, 56229},
{ 47630, 49218, 50806, 52394, 53982, 55570, 57158, 58746, 60334, 61922},
{ 52329, 54073, 55817, 57561, 59305, 61049, 62793, 64537, 66281, 68025},
{ 62722, 64813, 66904, 68995, 71086, 73177, 75268, 77359, 79450, 81541},
{ 74584, 77070, 79556, 82042, 84528, 87014, 89500, 91986, 94472, 96958},
{ 88136, 91074, 94012, 96950, 99888, 102826, 105764, 108702,11640,114578},
{ 103672, 107128, 110584, 114040, 117496, 120952, 124408,127864, 1, 2}};
My goal is to std::cout in the same order it is displayed above so it prints each value in the first array pay_scale[0][n++]
then moves onto pay_scale[1][[n++]
then moves onto pay_scale[2][n++] etc. until it reaches pay_scale[14]
As of right now I just have:
for (int i = 0; i < 10; i++) {
std::cout << "[" << pay_scale[n][i] << "]" << "\t";
}
And n = 0
I am having trouble indexing it without it jumping to the next array before it finishes the first one.
I must say I am new to cpp as I am sure you can see, any guidance is appreciated.
Thank you!

Here's the way the cool kids do it. :-)
for (const auto &row : pay_scale) {
for (auto col : row) {
std::cout << col << " ";
}
std::cout << "\n";
}

Why not use something more like this which loops through all the array:
for(int i = 0; i<15; i++)
{
for(int n = 0; n<10; n++) cout<< "["<< pay_scale[i][n]<<"]\t";
cout<<endl;
}
Hope this helps.

Related

Return struct element from vector c++

I'm new to C++ and I'm trying to return a struct from a vector of structs by using 2 search criteria.
The function find_city is returning me everything from the defined range, regardless of whether it exists inside the vector of struct.
Here's my code:
struct cityLoc
{
int hRange;
int vRange;
int cityCode;
string cityName;
};
vector<cityLoc> cl1;
// the vector has already been preloaded with data
// function to return my struct from the vector
cityLoc find_city(int hRange, int vRange)
{
for (size_t i = 0; i < cl1.size(); i++)
{
if ((cl1[i].hRange = hRange) && (cl1[i].vRange = vRange))
{
return cl1[i];
}
}
}
int main()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j <= 8; j++)
{
cityLoc this_city;
this_city = find_city(i, j);
cout << this_city.hRange << ", " << this_city.vRange << endl;
}
}
return 0;
}
Also, aside from this question, I was previously looking into std::find_if and didn't understand it. If I have the following code, what is the output? How do I modify it such that it returns a struct?
auto it = find_if(cl1.begin(), cl1.end(), [](cityLoc& cl) { return cl.hRange == 1; } );
You have a bug here:
if ((cl1[i].hRange = hRange) && (cl1[i].vRange = vRange))
Those = are assignments, not comparisons! Please enable compiler warnings and you won't be hurt by such obvious typos in future.
std::find_if will return the iterator to the found struct entry if it is successful, std::vector::end() otherwise. So, you should first validate the returning iterator if it is valid or not.
For example:
auto it = std::find_if( cl1.begin(), cl1.end(),
[](const cityLoc& cl) { return cl.hRange == 1; } );
if ( it == cl1.end() )
{
// ERROR: Not found! Return error code etc.
return -1;
}
// And, if found, process it here...
std::cout << it->hRange << '\n';
std::cout << it->vRange << '\n';
The criteria (predicate) part in std::find_if is a lambda expression.

c++ String returning with an extra char

I have tested my program and am certain right before being returned the string in my function equals "card001". But the returned value equals "card0011". I have no idea how this even happens. Help me before I lose my mind. ;)
std::string function_cardTexture(int card) {
//removes the last 1
card = card - 10000;
int ctr = 0;
card = floor(card / 10);
std::cout << card << std::endl;
//turn int card into a string
std::string a = static_cast<std::ostringstream*>(&(std::ostringstream() << card))->str();
//combines card and string a into one string
std::string nametext = "card00" + a;
std::cout << nametext << std::endl;
return (nametext);
}
void function_Battle(tempPlayer &Player, tempCard &card001) {
if (Player.Start == true) {
//Draw hand
for (int i = 0; i < Player.numDrawn; i++) {
int x = rand() % Player.deckSize + 0; ;
Player.Hand[i] = Player.Deck[x];
Player.Discarded[x] = 1;
}
Player.Start = false;
}
std::map<std::string, tempCard> Vars;
//draw hand
for (int i = 0; i < Player.handMax;i++) {
if (Player.Hand[i] != 0) {
sf::RectangleShape Card(sf::Vector2f(80.0f, 128.0f));
std::string nametext = function_cardTexture(Player.Hand[i]);
std::cout << nametext;
sf::Texture texture = Vars[nametext].Art;
Card.setTexture(&texture);
window.draw(Card);
}
}
}
Your problem is how you're printing things out without a newline in the function_Battle() function, so you're likely "smashing together" your new value with an old one. If you replace your main function with just a loop with clearer printing of values, you can see you don't have a problem:
http://coliru.stacked-crooked.com/a/8d1e4f51643b84b9
That link will go to an online compiler where I just replaced the calling function with a loop that makes numbers. It even supplies a negative one.

C++ Calculating Shortest Path in a Directed Graph

I am tasked with writing a program to maintain the representation of a simple network(weighted directed graph) and compute the best path between two given nodes upon request.
Currently, I am attempting to write a function to compute the simplest between two nodes, however, when attempting to run my program, I get two specific error
Severity Code Description Project File Line Suppression State
Error C3863 array type 'bool [openNode]' is not assignable P 127
and
Severity Code Description Project File Line Suppression State
Error C3863 array type 'int [openNode]' is not assignable
I am unable to debug since these two primary errors are not allowing my program to run. Is there any particular reason for these errors?
Thanks in advance!
This is the node structure defined in Graph.h
struct GraphNode
{
char ID;
std::string name;
int inNodes = 0;
int outNodes = 0;
std::vector<std::pair<GraphNode*, int>> connection;
int connections = 0;
};
And here is the particular code that causes the errors.
#include "Graph.h"
std::vector<GraphNode*> _graph;
int openNode = 0;
//Obligatory constructor
void Graph()
{
}
void shortestPath(char fromNode, char toNode)
{
bool known[openNode];
int distance[openNode];
GraphNode* previous[openNode];
int numbChecked = 0;
for (int i = 0; i < openNode; i++)
{
known[i] = false;
distance[i] = 999999;
previous[i] = nullptr;
}
distance[findNode(fromNode)] = 0;
while (numbChecked < openNode)
{
int smallestUnknown = 9999999;
int locationOfSmall = 0;
for (int i = 0; i < openNode; i++)
{
if (known[i] == false && distance[i] < smallestUnknown)
{
smallestUnknown = distance[i];
locationOfSmall = i;
}
}
if (distance[locationOfSmall] == 0)
{
previous[locationOfSmall] = nullptr;
}
known[locationOfSmall] = true;
numbChecked++;
if (_graph[locationOfSmall]->outNodes > 0)
{
for (int i = 0; i < _graph[locationOfSmall]->outNodes; i++)
{
int newDistanceLocation = findNode(_graph[locationOfSmall]->connection[i].first->ID);
if (known[newDistanceLocation] == false && (distance[locationOfSmall] + _graph[locationOfSmall]->connection[i].second) < distance[newDistanceLocation])
{
distance[newDistanceLocation] = distance[locationOfSmall] + _graph[locationOfSmall]->connection[i].second;
previous[newDistanceLocation] = _graph[locationOfSmall];
}
}
}
}
int destination = findNode(toNode);
std::string output;
std::string charTransfer;
charTransfer = toNode;
output = charTransfer;
while (previous[destination] != nullptr)
{
destination = findNode(previous[destination]->ID);
charTransfer = _graph[destination]->ID;
output = charTransfer + "->" + output;
}
if (_graph[destination]->ID != fromNode)
{
std::cout << "The nodes are not connected." << std::endl;
}
else
{
std::cout << "The path is: " << output << std::endl;
std::cout << "The distance is: " << distance[findNode(toNode)] << std::endl;
}
}
Any change suggestions would be much appreciated!
You have invalid code at the beginning of your shortestPath function:
bool known[openNode];
int distance[openNode];
GraphNode* previous[openNode];
You cannot use variables to create arrays on the stack (which is what you are trying to do there), because the compiler doesn't know the value of openNode at compile time (which is needed to determine the stack size).
Why don't you use a vector, like:
std::vector<bool> known(openNode, false);
std::vector<int> distance(openNode, 999999);
std::vector<GraphNode*> previous(openNode, nullptr);
Using this method makes the for loop below obsolete aswell.

Find char* element in array of char* in C++

I'm trying to write function that search for char * element in array of char* and the function start check this element, if the element exist in the array I will have "found", if not it should be "inserted" and the element added to the array.
I wrote this code but I cannot know how to try it, the program always gives me exception, what can I do to check the element in my pointer array?
void checkFunction(char*myArray[], char *element,bool flag)
{
for (int i = 0; i < strlen(*myArray) ; ++i)
{
if (myArray[i] == element)
{
flag = true;
}
}
*myArray = element;
flag = false;
if (flag)
{
cout << "Found" << endl;
}
else
{
cout << "Inserted" << endl;
}
}
C++ Way
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[]) {
vector<string> myStrings { "One", "Two", "Three" };
// std::find() finds the first element that matches a value
auto it = find(begin(myStrings), end(myStrings), "Twooo");
if (it != end(myStrings)) {
cout << "We found this string; do something..." << endl;
}
}
Few remarks regarding your function:
1.Why do you need the third parameter bool flag, instead of having it as local variable?
2.If you want to expand an array you should copy the old to a newly allocated and then add the new element, you can not just do: *myArray = element;
3.If you want to iterate through the array length/ size, instead of:
for (int i = 0; i < strlen(*myArray) ; ++i)
pass an additional parameter to your function, that indicates the number of elements in the array.
With std::string and std::vector you could do something like:
void check_insert (std::vector<std::string>& v, std::string& c) {
for (auto i = 0; i < v.size(); ++i) {
if (v[i] == c) {
std::cout << "Found!\n";
return;
}
}
v.push_back(c);
std::cout << "Inserted!\n";
}

Weird function seems to change vector values

I have to program something that filters email by checking if the source of the email is found in a blacklist or if any word in the email's content is found in a list of blocked words.
Here's the function that filters the email.
void filterEmail(vector<email>& amis, vector<email>& corbeille,
vector<email>& rejete, vector<email>& emails,
vector<string> b, vector<string> w,
vector<string> spam)
{
bool isListed(email, vector<string>);
bool isSpam(email, vector<string>);
for(vector<email>::size_type i = 0; i < emails.size();)
{
if(isListed(emails[i], b))
{
corbeille.push_back(emails[i]);
emails.erase(emails.begin() + i);
}
else i++;
}
for(vector<email>::size_type i = 0; i < emails.size();)
{
if(isListed(emails[i], w))
{
amis.push_back(emails[i]);
emails.erase(emails.begin() + i);
}
else i++;
}
for(vector<email>::size_type i = 0; i < emails.size();)
{
if(isSpam(emails[i], spam))
{
cout << emails[i].source << " " << emails[i].content[0];
rejete.push_back(emails[i]);
emails.erase(emails.begin() + i);
}
else i++;
}
return;
}
I have a really weird problem with the part where it checks for spam words in the content (3rd for loop)
after a few test cout's I realised after the first time isSpam returns true, the content of the email changes to the line where it first returns true, and all the next emails return true.
bool isSpam(const email e, const vector<string> motsinterdis)
{
for(vector<string>::size_type i = 0; i < e.content.size(); ++i)
{
for(vector<string>::size_type j = 0; j < motsinterdis.size(); ++j)
{
if(string::npos != e.content[i].find(motsinterdis[j]))
{
cout << e.source << endl;
cout << motsinterdis[j] << " found in " << e.content[i] << endl;
return true;
}
}
}
return false;
}
I have an Struct Email, which contains a vector content. Sorry for the french variables in there :P
Hope I've been clear enough,
Thanks a lot.