how to change vector elements by passing them to a function
I've got a c++ exam coming up soon, so I decided to study by writing a random program that would implement most of the material that's been covered in the class so far. What I came up with is a program that reads numerical data from an input file, copies it to a vector, performs a few calculations via a few custom functions, sorts the vector from lowest value to highest, and displays the data in standard output.
Everything works fine, except for the sorting function. I can't seem to figure out how to change the values of a vector. When running the program the vector elements stay in their original order. I'm pretty sure I need to reference the vector in order for the function to be able to change the actual data, but I can't figure out how to do so properly.
Here's the code (it requires a file named "input.txt" to work) :
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void icountSumAvg(vector<double>, int, int &icount, double &sum, double &avg);
void display(int, double, double);
void display(int, double, double, vector<double>, int);
void swap(vector<double>, int);
int main()
{
ifstream ifile;
const string FILENAME = "input.txt";
ifile.open(FILENAME);
int count = 0;
double sum = 0, avg = 0;
if (!(ifile.fail()))
{
bool testSwap = true; // displays each element if true
vector<double> vect;
double value = 0.0;
while (!ifile.eof())
{
ifile >> value;
vect.push_back(value);
}
int vectSize = vect.size();
icountSumAvg(vect, vectSize, count, sum, avg);
if (testSwap == true)
{
swap(vect, vectSize);
display(count, sum, avg, vect, vectSize);
}
else
display(count, sum, avg);
ifile.close();
}
else
cout << "There was an error opening the file: " << FILENAME << endl;
system("pause");
}
void icountSumAvg(vector<double> values, int size, int &icount, double &sum, double &avg)
{
for (int i = 0; i < size; i++)
{
icount++;
sum += values[i];
}
avg = sum / icount;
}
void swap(vector<double> values, int size)
{
double temp;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < i; j++)
{
if (values[j] < values[i])
{
temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
}
void display(int count, double sum, double avg, vector<double> values, int size)
{
for (int i = 0; i < size; i++)
{
cout << "Element " << i + 1 << ": " << values[i] << endl;
}
cout <<"Total count: " << count << endl
<< "Total sum: " << sum << endl
<< "Average of numbers: " << avg << endl;
}
void display(int count, double sum, double avg)
{
cout <<"Total count: " << count << endl
<< "Total sum: " << sum << endl
<< "Average of numbers: " << avg << endl;
}
2 answers
-
answered 2019-11-14 05:27
codtiger
In the
swap
function, the values function doesn't receive a pointer/reference to the vector object, therefore accepting a copy of the object, and as the method is void you are just changing the value of the copy not the object itself. -
answered 2019-11-14 05:35
seccpur
You're swap() function is only modifying the vector copied to the function. Send the vector by reference to the swap() function to get the desire effect. This will avoid extra copying also.
Since icountSumAvg() and display() is not supposed to modify the vector parameter, declare them as const reference too like so:
void swap(vector<double>&, int); void icountSumAvg(const vector<double>&, int, int &icount, double &sum, double &avg); void display(int, double, double, const vector<double>&, int);
See also questions close to this topic
-
How to end AsyncWebServer ESP32
Let's say that I'd like to end my server my code looks like this:
#include <WiFi.h> #include <ESPAsyncWebServer.h> AsyncWebServer server(7777); const char* ssid = "SSID"; const char* password = "PASSWORD"; void notFound(AsyncWebServerRequest *request) { Serial.println(request->url()); request->send(404, "text/plain", "Not found"); } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("WiFi Failed!"); return; } server.onNotFound(notFound); server.begin(); server.end(); } void loop() { }
Please note that I know that this code will close the server as soon as it starts but It's just the shortest code to reproduce my problem. The ESP32 automatically resets after it reaches the line server.end(); The error message
rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1216 ho 0 tail 12 room 4 load:0x40078000,len:9720 ho 0 tail 12 room 4 load:0x40080400,len:6352 entry 0x400806b8 assertion "invalid socket state for sent callback" failed: file "/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/lwip/lwip/src/core/tcp.c", line 1842, function: tcp_sent abort() was called at PC 0x40101537 on core 1 Backtrace: 0x4008c434:0x3ffb1e90 0x4008c665:0x3ffb1eb0 0x40101537:0x3ffb1ed0 0x40119582:0x3ffb1f00 0x400d5e7d:0x3ffb1f20 0x400d5149:0x3ffb1f40 0x400d10d2:0x3ffb1f60 0x400d7e87:0x3ffb1fb0 0x40088b7d:0x3ffb1fd0 Rebooting... ets Jun 8 2016 00:22:57
-
Opencv Kalman tracking without new observation
How can I use Kalman for tracking without new observations? In my case I want to
predict()
when there is no detection. In more detail... I want to use kalman when there is detection lost (In my case, when object is detected in previous frame but not detected in the current frame. I don't have actual detection as input forcorrect()
). Please let me know how to use kalman filter for tracking of object when detection lost and there is no actual object detected location,only we have last detected location. Thanks in advance. -
Why do people don't talk about the problem of memory consumption when using classes?
People talk about why you should use classes over regular functions and why OOP is best but why they don't talk about problem of memory consumption when using classes?
For example when you create a class with 4 int + 4 char + 4 float variables and declare its object in main function the object would take X bytes in memory where X would be sum of memory consumption by 4 int + 4 char + 4 float. Even if you are using just 1 int data member the object is unnecessarily consuming more memory. While this is not the case with regular functions.
Can anyone please explain why people don't talk about this? Or in other words, why people don't consider this factor while using classes?
For reference, let's talk in C++ context.
-
How to use recursive function to produce a 1-D array in PHP that contains a hierarchical comment reply system?
I have 2 tables. Table 'comments' contains all the comments with cid ,comment as fields. and another table 'reply' which consists of cid and rpid which stores which comment is the reply of which comment.
function array_gen($c, $array, $total, $conn, $f) { $array[] = $c; $sql = "SELECT rpid FROM reply WHERE cmid = '$c';"; $st = $conn->query($sql); $st->setFetchMode(PDO::FETCH_ASSOC); $rpid = $st->fetchAll(); $count = $st -> rowCount(); if ($count > 0) { foreach ($rpid as $r) { $array = array_gen($r['rpid'], $array, $total, $conn, $f); } } else { echo $c; return $array; } while ($f <= $total) { if (! in_array($f, $array)) { $array = array_gen($f, $array, $total, $conn, $f); } $f++; } return $array; }
I tried out a function with parameters total number of comments ($total), first comment ($c), empty array ($array), a flag variable $f initialised to value of $c and a PDO connection variable $conn. It works perfectly upto 2 level of comment-reply. But when it comes to 3rd level i.e, a reply is given to another reply, it starts misbehaving. Function return is not working properly inside foreach loop.
-
invalid regular expression, reason 'Invalid contents of {}' in function with R
I'm making macro with
function
mytable
inmoonBook
package will be used infunction
macro.mytable
function makes descriptive table of population quickly.fun<-function(i,j) { j<-mytable(i~var1+var2+var3,data=rawdata) return(j) } fun(i=criteria,j=out)
However, the error appeared.
' i ' is an invalid column name: Instead ' (other value name) ' is used
I thought that
mytable
function can't recognize the macro object,i
.With help of this post (object not found in summarise with macro(function) in r) I put the double parentheses around
i
.But the error appeared again.
Error in grepl(pattern, x, ignore.case = TRUE) : invalid regular expression, reason 'Invalid contents of {}'
I tried
enquo
and!!
. But error still appeared.Error in which(grepl(pattern, x, ignore.case = TRUE)) : argument to 'which' is not logical
Please help me know what was the problem.
-
Why is nothing being passed to my overloaded function?
first poster here. To start things off, I'm using .NET 4.8 and C#. I'm having some issues with an overloaded function that doesn't seem to be getting any parameter input. Essentially what my functions are trying to do is take either a single object or a list of objects (all of a custom class 'Card') and determine if one of them has the same faction as the object calling the function. However, when I debug the the program, the first function works perfectly and as expected, but the second function doesn't seem to be getting any input at all; it gets an object with length 0. 'Factions' is a namespace-wide public enum; I don't think there are any problems there.
Class and function definition:
public class Card { /* Constructors, variables, and other functions left out for simplicity */ public bool SameFaction(Card card) { if (card.Faction.Equals(this.Faction)) return true; return false; } public bool SameFaction(List<Card> hand) { foreach (Card card in hand) { if (card.Faction.Equals(this.Faction)) { return true; } } return false; } }
Implementation:
Card card1 = new Card(Factions.faction1); List<Card> listOfCards = new List<Card>(); { new Card(Factions.faction1); new Card(Factions.faction2); new Card(Factions.faction3); new Card(Factions.faction4); }; card1.SameFaction(new Card(Factions.faction1)); // Returns true card1.SameFaction(listOfCards); // Returns false, and when debugging, shows input as being an object of length 0
Basically I'm wondering what I'm doing wrong, and also if there's a better way of doing this. I'm self-taught, so any and all suggestions are helpful. Thanks!
-
Character count in Python
The task is given: need to get a word from user, then total characters in the word must be counted and displayed in sorted order (count must be descending and characters must be ascending - i.e., if the user gives as "management" then the output should be
**a 2 e 2 m 2 n 2 g 1 t 1**
this is the code i written for the task:
string=input().strip() set1=set(string) lis=[] for i in set1: lis.append(i) lis.sort() while len(lis)>0: maxi=0 for i in lis: if string.count(i)>maxi: maxi=string.count(i) for j in lis: if string.count(j)==maxi: print(j,maxi) lis.remove(j)
this code gives me following output for string "management"
a 2 m 2 e 2 n 2 g 1 t 1
m & e are not sorted. What is wrong with my code?
-
Sort list by keyword matched in data attribute
I have a long list with basic JavaScript search. The search functions uses regex to test if certain conditions are met, and hide those do not meet. I am trying to sort the list and prioritize those found in attribute 1, follow by items that have keyword matched in attribute 2. Scenario described as below.
My list
- Chocolate Caramels
- Garlic Mayonnaise
- Tomato Egg
- Scrambled egg
Currently - when I search for
egg
, it returns the list as below- Garlic Mayonnaise
- Tomato Egg
- Scrambled Egg
Aiming for - This is the result I am looking for
- Scrambled Egg
- Tomato Egg
- Garlic Mayonnaise
As we can see from the list,
Garlic Mayonnaise
does not haveEgg
in its product title, but search returns true becauseegg
is found in the data attribute, as shown in below.<li productname="Garlic Mayonnaise" data-desc="Contains egg">Garlic Mayonnaise</li>
Is there any way we can sort the list by keyword found in title and followed by those keyword found in data attribute?
My search function as in below
let productList = $('#productListUL li'); $.each(productList, function(_index, product){ let self = $(product), productId = self.attr('productid'), productName = self.attr('productname'), productDesc = self.attr('data-desc'); if ( regex.test(productId) || regex.test(productName) || regex.test(productDesc) ) { self.removeClass('hidden'); } else{ self.addClass('hidden'); } });
-
Sort posts alphabetically on a specific page in Wordpress
So, it should be a simple task, but I have no idea why it's not working by now. I have tried everything, every Google link is purple, so now I hope someone can tell me what it is, I'm doing wrong.
I should start by mentioning that it's a Divi theme, but I did get it to work a few months ago, but forgot how, and I can't recreate it now.
I'm just trying to sort the main query alphabetically (A-Z), but only on a page called recipes. The site have all the recipes as posts, together with their blog posts, but the blog posts are sorted by date and showed on a separate page, which works fine.
But weird stuff are happening, when I try and alter it. If I use this code, it actually works, but the blog page also get sorted alphabetically, which it shouldn't.
function foo_modify_query_order( $query ) { if (is_archive()) { $query->set( 'orderby', 'title' ); $query->set( 'order', 'ASC' ); } } add_action( 'pre_get_posts', 'foo_modify_query_order' );
Which doesn't make sense to me, since it's posts? Out of all the ways I've tried, it only sorts if I use is_archive().
If I try to make it check for a specific page first, like
&& is_page('recipes')
I get an error.If I just add
if (is_page('recipes')){ echo 'Recipes'; }
it works, but if I try to add the sorting inside, I get nothing.So partially working, but I can't combine the two. Is it a Divi issue or am I doing it wrong? Hope anyone can help, I've tried so many different things now. Cheers :)
-
Syscall param read(buf) points to unaddressable byte(s) when Vector goes out of scope
I have written a box car filter on binary image data using C++ vectors.
The program runs successfully and I get all the required output without any issue. But, when the code exits, i.e., when the vector variable goes out of scope, I get a segmentation fault.
I got the same issue when I closed/cleared the vector in the end of loop using
erase
,clear
,vector<vector<float> >().swap
etc.I also tried running the code in a separate function, where the vector goes out of scope automatically, and the program dumps memory right after processing single image. (each loop processes one image)
Complete program:
#include <iostream> #include <string> #include <vector> #include <cmath> #include <algorithm> #include <fstream> using namespace std; void createhdr(string,int,int); void avg(string,string,int,int,string); int main(int argc, char** argv) { if(argc < 5) { cerr<<"1. Input Path"<<endl; cerr<<"2. Rows"<<endl; cerr<<"3. Cols"<<endl; cerr<<"4. Out Path"<<endl; exit(1); } string in_path(argv[1]); int rows = stoi(argv[2]); int cols = stoi(argv[3]); vector<string> C3_files; C3_files.emplace_back("C12_Real"); C3_files.emplace_back("C11"); C3_files.emplace_back("C12_Imag"); C3_files.emplace_back("C13_Real"); C3_files.emplace_back("C13_Imag"); C3_files.emplace_back("C22"); C3_files.emplace_back("C23_Real"); C3_files.emplace_back("C23_Imag"); C3_files.emplace_back("C33"); for(auto vec: C3_files) { cout<<vec<<endl; } string out_path(argv[4]); cout<<"Inpath: "<<in_path<<endl; cout<<"Outpath: "<<out_path<<endl<<endl<<endl; vector<vector<float> > c; vector<vector<float> > C3; c = vector<vector<float> >(rows,vector<float>(cols,0.0f)); C3 = vector<vector<float> >(rows,vector<float>(cols,0.0f)); for(int i=0; i<9; i++) { cout<<"File "<<i+1<<": "<<endl; string inpath = in_path+"/"+C3_files[i]+".bin"; string outpath = out_path+"/"+C3_files[i]+".bin"; string hdrpath = out_path+"/"+C3_files[i]; cout<<"*"<<endl; ifstream c_f; cout<<"*"<<endl; ofstream C_f; cout<<"*"<<endl; c_f.open(inpath,ios::in|ios::binary); cout<<"*"<<endl; C_f.open(outpath,ios::out|ios::binary); cout<<"*"<<endl; cout<<"Inpath: "<<inpath<<endl; cout<<"*"<<endl; cout<<"Outpath: "<<outpath<<endl; cout<<"*"<<endl; cout<<"*"<<endl; cout<<"*"<<endl; c_f.read(reinterpret_cast<char *>(&c[0][0]),rows*cols*sizeof(float)); cout<<"*"<<endl; cout<<"*"<<endl; cout<<"Calculating ensemble average."<<flush; cout<<"*"<<endl; for(int j = 0; j < rows; j++) { for(int k = 0; k < cols; k++) { int sum = 0; int win = 3; for(int p = -win/2; p < win/2; p++) { int index_x = j + p; for(int q = -win/2; q < win/2; q++) { int index_y = k + q; if(index_x < 0 || index_y < 0 || index_x >= rows || index_y >= cols) { sum +=0; } else { sum += c[index_x][index_y]; } } } C3[j][k] = sum; } } cout<<"*"<<endl; cout<<"done."<<endl; cout<<"*"<<endl; C_f.write(reinterpret_cast<const char *>(&C3[0][0]),rows*cols*sizeof(float)); cout<<"*"<<endl; createhdr(hdrpath,cols,rows); cout<<"*"<<endl; c_f.close(); cout<<"*"<<endl; C_f.close(); cout<<"*"<<endl; // vector<vector<float> >(rows,vector<float>(cols,0.0f)).swap(c); // vector<vector<float> >(rows,vector<float>(cols,0.0f)).swap(C3); // avg(inpath,outpath,rows,cols,hdrpath); } c.clear(); cout<<"Meh!"<<endl; cout<<"That's all folks!"<<endl; return 0; } void avg(string inpath, string outpath, int rows, int cols, string hdrpath) { cout<<"*"<<endl; ifstream c_f; cout<<"*"<<endl; ofstream C_f; cout<<"*"<<endl; c_f.open(inpath,ios::in|ios::binary); cout<<"*"<<endl; C_f.open(outpath,ios::out|ios::binary); cout<<"*"<<endl; cout<<"Inpath: "<<inpath<<endl; cout<<"*"<<endl; cout<<"Outpath: "<<outpath<<endl; cout<<"*"<<endl; cout<<"*"<<endl; vector<vector<float> > c = vector<vector<float> >(rows,vector<float>(cols,0.0f)); cout<<"*"<<endl; c_f.read(reinterpret_cast<char *>(&c[0][0]),rows*cols*sizeof(float)); cout<<"*"<<endl; vector<vector<float> > C3 = vector<vector<float> >(rows,vector<float>(cols,0.0f)); cout<<"*"<<endl; cout<<"Calculating ensemble average."<<flush; cout<<"*"<<endl; for(int j = 0; j < rows; j++) { for(int k = 0; k < cols; k++) { int sum = 0; int win = 3; for(int p = -win/2; p < win/2; p++) { int index_x = j + p; for(int q = -win/2; q < win/2; q++) { int index_y = k + q; if(index_x < 0 || index_y < 0 || index_x >= rows || index_y >= cols) { sum +=0; } else { sum += c[index_x][index_y]; } } } C3[j][k] = sum; } } cout<<"*"<<endl; cout<<"done."<<endl; cout<<"*"<<endl; C_f.write(reinterpret_cast<const char *>(&C3[0][0]),rows*cols*sizeof(float)); cout<<"*"<<endl; createhdr(hdrpath,cols,rows); cout<<"*"<<endl; c_f.close(); cout<<"*"<<endl; C_f.close(); cout<<"*"<<endl; } void createhdr(string filename, int samples, int scans) { ofstream hdr(string(filename+".hdr")); hdr<<"ENVI"<<endl; hdr<<"description = {"<<endl; hdr<<" File Imported into ENVI.}"<<endl; hdr<<"samples = "<<samples<<endl; hdr<<"lines = "<<scans<<endl; hdr<<"bands = 1"<<endl; hdr<<"header offset = 0"<<endl; hdr<<"file type = ENVI standard"<<endl; hdr<<"data type = 4"<<endl; hdr<<"interleave = bsq"<<endl; hdr<<"sensor type = Unknown"<<endl; hdr<<"byte order = 0"<<endl; hdr<<"wavelenfth units = Unknown"; hdr.close(); cout<<"HDR file created."<<endl; }
Valgrind output
==3505== Memcheck, a memory error detector ==3505== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al. ==3505== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info ==3505== Command: ./C3_Boxcar.o /home/tarun/Documents/Work/Data/10Dec2019/extract/ML/scaled/C3 12087 512 /home/tarun/Documents/Work/Data/10Dec2019/extract/ML/scaled/C3/C3_BoxCar ==3505== Parent PID: 3056 ==3505== ==3505== Syscall param read(buf) points to unaddressable byte(s) ==3505== at 0x54C9230: __read_nocancel (syscall-template.S:84) ==3505== by 0x4EEA216: std::__basic_file<char>::xsgetn(char*, long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21) ==3505== by 0x4F24C08: std::basic_filebuf<char, std::char_traits<char> >::xsgetn(char*, long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21) ==3505== by 0x4F318EA: std::istream::read(char*, long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21) ==3505== by 0x4022F3: main (in /home/tarun/C3_Boxcar.o) ==3505== Address 0x5aff4a0 is 0 bytes after a block of size 2,048 alloc'd ==3505== at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==3505== by 0x405673: __gnu_cxx::new_allocator<float>::allocate(unsigned long, void const*) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x405456: std::allocator_traits<std::allocator<float> >::allocate(std::allocator<float>&, unsigned long) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x4050ED: std::_Vector_base<float, std::allocator<float> >::_M_allocate(unsigned long) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x404C1A: std::_Vector_base<float, std::allocator<float> >::_M_create_storage(unsigned long) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x404416: std::_Vector_base<float, std::allocator<float> >::_Vector_base(unsigned long, std::allocator<float> const&) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x405917: std::vector<float, std::allocator<float> >::vector(std::vector<float, std::allocator<float> > const&) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x40574E: void std::_Construct<std::vector<float, std::allocator<float> >, std::vector<float, std::allocator<float> > const&>(std::vector<float, std::allocator<float> >*, std::vector<float, std::allocator<float> > const&) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x405524: std::vector<float, std::allocator<float> >* std::__uninitialized_fill_n<false>::__uninit_fill_n<std::vector<float, std::allocator<float> >*, unsigned long, std::vector<float, std::allocator<float> > >(std::vector<float, std::allocator<float> >*, unsigned long, std::vector<float, std::allocator<float> > const&) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x4051ED: std::vector<float, std::allocator<float> >* std::uninitialized_fill_n<std::vector<float, std::allocator<float> >*, unsigned long, std::vector<float, std::allocator<float> > >(std::vector<float, std::allocator<float> >*, unsigned long, std::vector<float, std::allocator<float> > const&) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x404DB9: std::vector<float, std::allocator<float> >* std::__uninitialized_fill_n_a<std::vector<float, std::allocator<float> >*, unsigned long, std::vector<float, std::allocator<float> >, std::vector<float, std::allocator<float> > >(std::vector<float, std::allocator<float> >*, unsigned long, std::vector<float, std::allocator<float> > const&, std::allocator<std::vector<float, std::allocator<float> > >&) (in /home/tarun/C3_Boxcar.o) ==3505== by 0x4045B9: std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::_M_fill_initialize(unsigned long, std::vector<float, std::allocator<float> > const&) (in /home/tarun/C3_Boxcar.o) ==3505== ==3505== Warning: invalid file descriptor -1 in syscall writev() --3505-- VALGRIND INTERNAL ERROR: Valgrind received a signal 11 (SIGSEGV) - exiting --3505-- si_code=128; Faulting address: 0x0; sp: 0x802ca9e30 valgrind: the 'impossible' happened: Killed by fatal signal host stacktrace: ==3505== at 0x38091C12: ??? (in /usr/lib/valgrind/memcheck-amd64-linux) ==3505== by 0x38050E84: ??? (in /usr/lib/valgrind/memcheck-amd64-linux) ==3505== by 0x380510A9: ??? (in /usr/lib/valgrind/memcheck-amd64-linux) ==3505== by 0x380D4F7B: ??? (in /usr/lib/valgrind/memcheck-amd64-linux) ==3505== by 0x380E3946: ??? (in /usr/lib/valgrind/memcheck-amd64-linux) sched status: running_tid=1 Thread 1: status = VgTs_Runnable (lwpid 3505) ==3505== at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==3505== by 0x4F5B96C: void std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_construct<char*>(char*, char*, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21) ==3505== by 0x4F5B9CE: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21) ==3505== by 0x402600: main (in /home/tarun/C3_Boxcar.o) Note: see also the FAQ in the source distribution. It contains workarounds to several common problems. In particular, if Valgrind aborted or crashed after identifying problems in your program, there's a good chance that fixing those problems will prevent Valgrind aborting or crashing, especially if it happened in m_mallocfree.c. If that doesn't help, please report this bug to: www.valgrind.org In the bug report, send all the above text, the valgrind version, and what OS and version you are using. Thanks.
Output, after removing all the successfully printed text:
*** Error in `./C3_Boxcar.o': free(): invalid next size (normal): 0x00000000010bdcc0 *** ======= Backtrace: ========= /lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f47235637e5] /lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7f472356c37a] /lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f472357053c] ./C3_Boxcar.o[0x40547a] ./C3_Boxcar.o[0x405122] ./C3_Boxcar.o[0x404c84] ./C3_Boxcar.o[0x40447b] ./C3_Boxcar.o[0x403b6d] ./C3_Boxcar.o[0x40541d] ./C3_Boxcar.o[0x405093] ./C3_Boxcar.o[0x404baa] ./C3_Boxcar.o[0x4043a5] ./C3_Boxcar.o[0x4046c4] ./C3_Boxcar.o[0x403da4] ./C3_Boxcar.o[0x402705] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f472350c830] ./C3_Boxcar.o[0x401859] ======= Memory map: ======== 00400000-00409000 r-xp 00000000 08:13 123604203 /home/tarun/C3_Boxcar.o 00608000-00609000 r--p 00008000 08:13 123604203 /home/tarun/C3_Boxcar.o 00609000-0060a000 rw-p 00009000 08:13 123604203 /home/tarun/C3_Boxcar.o 010ab000-0406e000 rw-p 00000000 00:00 0 [heap] 7f471c000000-7f471c021000 rw-p 00000000 00:00 0 7f471c021000-7f4720000000 ---p 00000000 00:00 0 7f47231e3000-7f47232eb000 r-xp 00000000 08:11 51122365 /lib/x86_64-linux-gnu/libm-2.23.so 7f47232eb000-7f47234ea000 ---p 00108000 08:11 51122365 /lib/x86_64-linux-gnu/libm-2.23.so 7f47234ea000-7f47234eb000 r--p 00107000 08:11 51122365 /lib/x86_64-linux-gnu/libm-2.23.so 7f47234eb000-7f47234ec000 rw-p 00108000 08:11 51122365 /lib/x86_64-linux-gnu/libm-2.23.so 7f47234ec000-7f47236ac000 r-xp 00000000 08:11 51122486 /lib/x86_64-linux-gnu/libc-2.23.so 7f47236ac000-7f47238ac000 ---p 001c0000 08:11 51122486 /lib/x86_64-linux-gnu/libc-2.23.so 7f47238ac000-7f47238b0000 r--p 001c0000 08:11 51122486 /lib/x86_64-linux-gnu/libc-2.23.so 7f47238b0000-7f47238b2000 rw-p 001c4000 08:11 51122486 /lib/x86_64-linux-gnu/libc-2.23.so 7f47238b2000-7f47238b6000 rw-p 00000000 00:00 0 7f47238b6000-7f47238cc000 r-xp 00000000 08:11 51122503 /lib/x86_64-linux-gnu/libgcc_s.so.1 7f47238cc000-7f4723acb000 ---p 00016000 08:11 51122503 /lib/x86_64-linux-gnu/libgcc_s.so.1 7f4723acb000-7f4723acc000 rw-p 00015000 08:11 51122503 /lib/x86_64-linux-gnu/libgcc_s.so.1 7f4723acc000-7f4723c3e000 r-xp 00000000 08:11 59246590 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21 7f4723c3e000-7f4723e3e000 ---p 00172000 08:11 59246590 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21 7f4723e3e000-7f4723e48000 r--p 00172000 08:11 59246590 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21 7f4723e48000-7f4723e4a000 rw-p 0017c000 08:11 59246590 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21 7f4723e4a000-7f4723e4e000 rw-p 00000000 00:00 0 7f4723e4e000-7f4723e74000 r-xp 00000000 08:11 51118105 /lib/x86_64-linux-gnu/ld-2.23.so 7f4723fb3000-7f4724046000 rw-p 00000000 00:00 0 7f4724070000-7f4724073000 rw-p 00000000 00:00 0 7f4724073000-7f4724074000 r--p 00025000 08:11 51118105 /lib/x86_64-linux-gnu/ld-2.23.so 7f4724074000-7f4724075000 rw-p 00026000 08:11 51118105 /lib/x86_64-linux-gnu/ld-2.23.so 7f4724075000-7f4724076000 rw-p 00000000 00:00 0 7fffafd70000-7fffafd91000 rw-p 00000000 00:00 0 [stack] 7fffafd92000-7fffafd94000 r--p 00000000 00:00 0 [vvar] 7fffafd94000-7fffafd96000 r-xp 00000000 00:00 0 [vdso] ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall] [1] 10287 abort (core dumped) ./C3_Boxcar.o /home/tarun/Documents/Work/Data/10Dec2019/extract/ML/scaled/C3
GDB where output ---
0x00007ffff74aa428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54 0x00007ffff74ac02a in __GI_abort () at abort.c:89 0x00007ffff74ec7ea in __libc_message (do_abort=do_abort@entry=2, fmt=fmt@entry=0x7ffff7605e98 "*** Error in `%s': %s: 0x%s ***\n") at ../sysdeps/posix/libc_fatal.c:175 0x00007ffff74f537a in malloc_printerr (ar_ptr=<optimized out>, ptr=<optimized out>, str=0x7ffff7605ff0 "free(): invalid next size (normal)", action=3) at malloc.c:5006 _int_free (av=<optimized out>, p=<optimized out>, have_lock=0) at malloc.c:3867 0x00007ffff74f953c in __GI___libc_free (mem=<optimized out>) at malloc.c:2968 0x000000000040547a in __gnu_cxx::new_allocator<float>::deallocate(float*, unsigned long) () 0x0000000000405122 in std::allocator_traits<std::allocator<float> >::deallocate(std::allocator<float>&, float*, unsigned long) () 0x0000000000404c84 in std::_Vector_base<float, std::allocator<float> >::_M_deallocate(float*, unsigned long) () 0x000000000040447b in std::_Vector_base<float, std::allocator<float> >::~_Vector_base() () 0x0000000000403b6d in std::vector<float, std::allocator<float> >::~vector() () 0x000000000040541d in void std::_Destroy<std::vector<float, std::allocator<float> > >(std::vector<float, std::allocator<float> >*) () 0x0000000000405093 in void std::_Destroy_aux<false>::__destroy<std::vector<float, std::allocator<float> >*>(std::vector<float, std::allocator<float> >*, std::vector<float, std::allocator<float> >*) () 0x0000000000404baa in void std::_Destroy<std::vector<float, std::allocator<float> >*>(std::vector<float, std::allocator<float> >*, std::vector<float, std::allocator<float> >*) () 0x00000000004043a5 in void std::_Destroy<std::vector<float, std::allocator<float> >*, std::vector<float, std::allocator<float> > >(std::vector<float, std::allocator<float> >*, std::vector<float, std::allocator<float> >*, std::allocator<std::vector<float, std::allocator<float> > >&) () 0x00000000004046c4 in std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::_M_erase_at_end(std::vector<float, std::allocator<float> >*) () 0x0000000000403da4 in std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::clear() () 0x0000000000402705 in main ()
-
Create a class in python for a n-dimensional vector. Numpy, scipy and similar not allowed
I beg your help for some issue with the creation of a class that computes common operations for n-dimensional vectors (sumation, dot product, cross product, etc.)
I have problems just at the begining:
class nVector: ''' Our goal is o create a class to work with nD vectors''' def __init__(self,*args): '''Construction of the nD vector with n arguments''' r=[] '''empty list where the coordinates will be gathered''' for i,xi in enumerate(args): self.i=xi r=r+[xi] self.r=r return
I used the r list to string it afterwards and be able to print and get to see something. The main problem is that if i write self.1 in the terminal I expect to get the first coordinate, self.2 the second and so on, but it is returning error:
n=nVector(1,1,1,1) n.1 File "<ipython-input-9-a30c5b21dbaf>", line 1 n.1 ^ SyntaxError: invalid syntax
Anyone knows how could get gthis fixed?
Another problem is that i have no clue for performing vector sumation.
Thanks to you all
-
How do I get a sequence of numbers to sum to a triangular number?
Can anyone help me set up this program? Initially I tried loading a string of numbers into the vector playHistory but I am already getting errors on that part. Here is my initial code:
vector<vector<int>> playHistory; string sequence; cout << setw(10) << "" << "Enter a sequence of positive numbers. Enter 0 when done: "; getline(cin, sequence); istringstream is(sequence); while (is >> sequence) { playHistory.push_back(sequence); } Write code to meet these specifications: Precondition: A user supplied sequence of numbers in decreasing order (such as 5,5,4,3,2,1,1) which sum to some triangular number, Tn. Postcondition: A sequence of Stax moves printed to the console. A typical run with the first line entered by the user and the following line computed by the program is below: OUTPUT: Enter a sequence of positive numbers. Enter 0 when done: 1123450 The root loop size is = 6 It takes 6 moves to get to the steady state: 1 1 2 3 4 5 0 1 3 3 4 5 1 2 3 4 6 2 2 3 4 5 1 2 3 5 5 1 1 23 4 5 1 2 4 4 5 ///prototypes bool endState(vector <int> v); ///Return true only if the input is a vector of the form {1,2,3,...,k} void show_stacks(vector <int> v); ///Print the vector v void show_history(vector < vector <int> > history); ///Print the sequence of vectors in history bool is_new(vector <int> v, vector < vector <int> > history) ///Compare the vector v (the latest addition to history) with all the previous vectors in history. If there’s no match, return true. If there is a match , return false void move(vector <int >& v); ///Perform the Stax move on v ///note that , since v is passed by reference , it will change v. int main() { vector <int> vStax; vector <vector<int>> playHistory; ///Get the user’s input for the initial vector of stax ///and start building playHistory with the first vector. ///loop the moves , building the playHistory ///and checking at each loop ///for endState(vStax)) and is_new(vStax ,playHistory) ///When the a root loop is found (or an end state), display ///the number of moves it took to get there and the size of the root loop }