I am new to C++. I know the output would be 1024, 10.
I just have no clue as to why log would print out 10, instead of 1.
int n = 1024;
int log = 0;
for (int i = 1; i < n; i = i * 2);
log++;
cout << n << " " << log << endl;
I believe you are missing just the brackets if you are trying to iterate over the loop and print out the log.
int n = 1024;
int log = 0;
for (int i = 1; i < n; i = i * 2)
{
log++;
cout << n << " " << log << endl;
}
Related
I have this function that will split the string. After running it in a while loop of read file, the program will exit instead of continue the next step of functions.
vector <string> splitString (string str, string delim){
vector <string> result;
size_t pos = 0;
string token;
while ((pos = str.find(delim)) != std::string::npos){
token = str.substr(0, pos);
result.push_back(token);
str.erase(0, pos+delim.length());
}
if (!str.empty())
result.push_back(str);
return (result);
}
void readCityLocation(int ** cityMap){
ifstream inFile;
inFile.open(filename[0]);
string line;
while (getline(inFile, line)){
int xCoordinate;
int yCoordinate;
string xValue;
string yValue;
//Get xCoordinate...
vector <string> splitThis = splitString(line,",");
xValue = splitThis[0];
cout << line;
}
An function called option2(), will create a table and call void readCityLocation( )
void option2(){
cout << endl << endl;
int ** table = new int * [gridXEnd + 1];
for (int i = 0; i < gridXEnd + 1; i++) {
table[i] = new int[gridYEnd + 1];
}
//Initialize all the array value in table to be 0
for (int i = 0; i < gridXEnd + 1; i++) {
for (int j = 0; j < gridYEnd + 1; j++) {
table[i][j] = 0;
//To be remove: Error Handling
//cout << table[i][j] << " Grid X: " << i << " Grid Y: " << j << endl;
}
}
readCityLocation(table);
}
I am fairly new to all this and can't figure out whats the problem. Any assistance is appreciated. Thank you.
I usually return an object of std::vector or std::map as an incoming reference paremeter(as funcVec2 and funcMap2 below). But it is a bit inconvenient when writing codes. So I think if I can use return value under c++11(as funcVec1 and funcMap1 below) because it will call move constructor but not copy constructor, so it maybe still spend only one construct time and no deconstruct as the form of incoming reference paremeter.
But I write the codes below to verify it and it turns out that funcVec1 and funcMap1 takes more times then funcVec2 and funcMap2. So I am confused now why funcVec1 and funcMap1 takes so long?
#include <iostream>
#include <vector>
#include <map>
#include <chrono>
using namespace std;
vector<int> funcVec1() {
vector<int >vec;
for (int i = 0; i < 10; ++i) {
vec.push_back(i);
}
return vec;
}
void funcVec2(vector<int>&vec) {
for (int i = 0; i < 10; ++i) {
vec.push_back(i);
}
return;
}
map<int, int> funcMap1() {
map<int, int>tmpMap;
for (int i = 0; i < 10; ++i) {
tmpMap[i] = i;
}
return tmpMap;
}
void funcMap2(map<int, int>&tmpMap) {
for (int i = 0; i < 10; ++i) {
tmpMap[i] = i;
}
}
int main()
{
using namespace std::chrono;
system_clock::time_point t1 = system_clock::now();
for (int i = 0; i < 100000; ++i) {
vector<int> vec1 = funcVec1();
}
auto t2 = std::chrono::system_clock::now();
cout << "return vec takes " << (t2 - t1).count() << " tick count" << endl;
cout << duration_cast<milliseconds>(t2 - t1).count() << " milliseconds" << endl;
cout << " --------------------------------" << endl;
vector<int> vec2;
for (int i = 0; i < 100000; ++i) {
funcVec2(vec2);
}
auto t3 = system_clock::now();
cout << "reference vec takes " << (t3 - t2).count() << " tick count" << endl;
cout << duration_cast<milliseconds>(t3 - t2).count() << " milliseconds" << endl;
cout << " --------------------------------" << endl;
for (int i = 0; i < 100000; ++i) {
map<int, int> tmpMap1 = funcMap1();
}
auto t4 = system_clock::now();
cout << "return map takes " << (t4 - t3).count() << " tick count" << endl;
cout << duration_cast<milliseconds>(t4 - t3).count() << " milliseconds" << endl;
cout << " --------------------------------" << endl;
map<int, int>tmpMap2;
for (int i = 0; i < 100000; ++i) {
funcMap2(tmpMap2);
}
auto t5 = system_clock::now();
cout << "reference map takes " << (t5 - t4).count() << " tick count" << endl;
cout << duration_cast<milliseconds>(t5 - t4).count() << " milliseconds" << endl;
cout << " --------------------------------" << endl;
return 0;
}
you are not only meassuring the time for your operations, you also include the printouts. this is suboptimal.
you should measure performance in release mode. be aware that you are not doing anything usefull with your objects and the optimizer may throw away most of your code you wanted to measure.
the comparisons are not "fair". for example in your map1 case you are constructing an empty map, fill it (memory allocations happen here) and then you throw it away. in the map2 case you are reusing the identical map object over and over again. you are not allocating memory over and over again.
My program can't read all of the data from my MarvelIn.txt file.
It reads about 29 spaces in, and MarvelIn.txt contains only 9 entries, then I get a runtime error.
I think I have all the syntax right, however this is the only error I have. It will not output to the output file "MarvelOut.txt".
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <stdio.h>
using namespace std;
struct sstruct
{
string first, last;
string department;
int salary;
};
void init2(sstruct s[50])
{
int maxarray = 50;
sstruct init = { "Darth", "Vader", "None", 0 };
for (int i = 0; i < maxarray; i++) {
s[i] = init;
cout << "init: " <<s[i].first<<endl;
}
}
void read(sstruct s[50], int &nums)
{
int maxarray = 50;
ifstream inf("MarvelIn.txt");
int i = 0;
while (!inf.eof())
{
inf >> s[i].first >> s[i].last >> s[i].department >> s[i].salary;
cout << "read: "<<s[i].first<<s[i].last << s[i].department <<
s[i].salary << endl;
i++;
}
nums = i;
}
void avg(sstruct s[50], int &nums, double &average2)
{
int maxarray = 50;
int i;
for (i = 0; i < nums; i++)
average2 += s[i].salary;
average2 /= nums;
}
void print(sstruct s[50], int nums, double &average2)
{
int maxarray = 50;
ofstream outf("MarvelOut.txt");
int i = 0;
string temp;
outf << "the number of professors is: " << nums << endl;
cout << "the number of professors is: " << nums << endl;
outf << endl << "The average salary of the professors is: " << average2 << endl;
outf << "Advisor " << "Major " << " Department " << "Salary " << endl;
for (i = 0; i < nums; i++)
{
temp= s[i].last + "," + s[i].first;
cout << "last, first " << temp << endl;
outf << left << setw(20) << temp << right << setw(5)<< s[i].department << setw(5) << s[i].salary << setw(8) << endl;
}
outf << endl << endl;
}
void swap(sstruct &a, sstruct &b)
{
sstruct temp;
temp=a;
a=b;
b=temp;
}
void bubbleSort(sstruct s[50], int &nums)
{
int maxarray = 50;
int i, j;
bool swapped;
for (i = 0; i < nums - 1; i++)
{
swapped = false;
for (j = 0; j < nums - i - 1; j++)
{
if (s[j].department > s[j + 1].department)
{
swap(s[j], s[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
int main() {
int nums=0;
double average3=0.0;
const int maxarray = 50;
sstruct s[maxarray];
init2(s);
print(s, nums, average3);
read(s, nums);
cout << "numsfirst: " << nums << endl;
avg(s, nums, average3);
cout << "nums" << nums << endl;
bubbleSort(s,nums);
print(s, nums, average3);
system("pause");
return 0;
}
I have the following code but the pop() function doesn't work I don't
know why.
#include < iostream >
#include < fstream >
#include < sstream >
#include < string >
#include < queue >
using namespace std;
int quantum;
struct process {
string name;
int arrival;
int burst;
int priority;
};
process parseProcess(string s)
//parse the given string s to find the process information
{
process p;
stringstream lineStream;
lineStream.str(s);
string item;
getline(lineStream, item, '$');
p.name = item;
getline(lineStream, item, '$');
p.arrival = stoi(item);
getline(lineStream, item, '$');
p.burst = stoi(item);
getline(lineStream, item, '$');
p.priority = stoi(item);
cout <<
p.name << "\t" << p.arrival << "\t" << p.burst << "\t" << p.priority << "\t" << endl;
return p;
}
void second_write(queue < process > s, int n, int quantum) {
int * burst_Time = new int[n], total = 0,
total_turn_arround = 0;
float avgwaiting_time = 0, avgturn_arround =
0;
int * remaining_burst_time = new int[n];
int * waitting_time = new
int[n];
int * turn_arround_time = new int[n]; //now queue doesn't pop
Why ? ? ? ? ? process temp = s.front();
process p;
queue < process > qtemp;
for (int i = 0; i < n; i++) {
p.name = temp.name;
p.arrival = temp.arrival;
p.burst = temp.burst;
burst_Time[i] = p.burst;
p.priority = temp.priority; * * s.pop(); * * qtemp.push(p);
cout
<< temp.name << "\t" << temp.arrival << "\t" << temp.burst << "\t" <<
temp.priority << endl;
}
for (int i = 0; i < n; i++) {
remaining_burst_time[i] = burst_Time[i];
}
while (1) {
bool finished = true;
for (int i = 0; i < n; i++) {
if (remaining_burst_time[i] > 0) {
finished = false;
if (remaining_burst_time[i] > quantum) {
total += quantum;
remaining_burst_time[i] -= quantum;
} else {
total += remaining_burst_time[i];
waitting_time[i] = total - burst_Time[i];
remaining_burst_time[i] = 0;
}
}
}
if (finished == true) break;
}
for (int i = 0; i < n; i++) {
turn_arround_time[i] = burst_Time[i] - waitting_time[i];
}
for (int i = 0; i < n; i++) {
total += waitting_time[i];
total_turn_arround += turn_arround_time[i];
}
avgturn_arround =
total_turn_arround / n;
avgwaiting_time = total / n;
int w = 0;
while (!qtemp.empty()) {
process temp2 = qtemp.front();
qtemp.pop();
}
}
int main() //it takes two arguments 1:inputFile name,
2: outputFile name {
string fileName;
cout << "enter file name " <<
endl;
cin >> fileName;
cout << "Enter quantum";
cin >> quantum;
ifstream infile(fileName);
string line;
queue < process > q;
while (getline(infile, line)) {
process p = parseProcess(line);
q.push(p);
}
int Length = q.size();
second_write(q, Length, quantum);
/*Your code must be written here in order to sort the processes in
the queue in terms of the chosen cpu scheduling algorithm. Your code
also needs to calcualte average wating time and average turnarround
time. Finally your code needs to print the Gantt chart, waiting time
for each process and the average waiting time and the average
turnaround time on the screen */
return 0;
}
Working under a time crunch here. Struggling to understand exactly what this problem is asking. Any help or pointers in the right direction would be greatly appreciated! Thanks in advanced.
The original problem is based on this given information:
for (int k = 0; k < 2*n; k++) {
cout << k << endl;
for (int i = k+1; i < n; i++)
{
m[i][j] = a[i][j] + b[i][j];
cout << m[i][j] << endl;
}
cout << i * k << endl;
}
For T(n) = http://www4c.wolframalpha.com/Calculate/MSP/MSP63941h503ff0a609230100002eieg6bhfe5gi70g?MSPStoreType=image/gif&s=23&w=167.&h=49.
And here is my problem:
Modify the code above to find the number of times the basic operation occurs (i.e. how many times does it go in the inner for loop?).
include
using namespace std;
int main()
{
int count = 0;
int n = 10;
for (int k = 0; k < 2*n; k++) {
cout << "outer: " << k << endl;
for (int i = k+1; i < n; i++) {
cout << "\tinner: " << i << endl;
count++;
}
}
cout << count << endl;
}
Write a summation based on the output of Step 1
Based on this, is T(n) equivalent to O(n) or O(n^2)
I'm confused about specifically what part 2 is asking for. But I found:
http://www4c.wolframalpha.com/Calculate/MSP/MSP4561hgb5f47a07e05g00000112a53ahh0670che?MSPStoreType=image/gif&s=30&w=109.&h=49.
To me this looks like O(N^2)?
I apologize for the formatting. I'm on mobile.
Let me see if I guide:
1. I think the count should be inside like this:
int main() {
int count = -1;
int n = 10;
for (int k = 0; k < 2*n; k++) {
count = 0;
cout << "outer: " << k << endl;
for (int i = k+1; i < n; i++) {
cout << "\tinner: " << i << endl;
count++;
}
cout << count << endl; //<<<here
}
}
Now collect the output (#here marker) and form a formula for the summation. I think this is Task#2.
Based on your formula (or summation) you will be able to generalize whether its o(n) or o(n^2).
This is definitely not linear.