Why is replacing an element of a vector so slow? - c++

I notice that amending (or replacing) an element in a large vector is consuming a lot of time when the vector is getting bigger, even when the element's place in the vector is known.
Is there an explanaition for this?
I use an unsorted set as an index. The code first tries to find the element in the set with set.find(). If the element not present in the set the code insert it at the end of the set and at the same time pushes it at the end of the vector.
If the element is found on position "x" of the set the data in the vector is replaced by using:
vector.at(x)=vector[x]+element.
When I skip the vector part and only insert the element in the set the code easily processes 95 million elements in less then 2 minutes. But when I add the vector part to it the code keeps on running for hours.
The file I'm importing is a semicolumn separated text, with below structure
2161182;Jutfaseweg;footway;no;7740068,13877901
2953564;Timorkade;cycleway;no;7785429,368846814,582743212,582743202,582743213,582743203,582743214,582743206,582743210,45200603
Each line represents a way. The ID's in the last element are waypoints of that particular way. Each element has a righthand neighbour, unless it is the last element of the way and based on the 4th element ("yes" or "no", meaning oneway or not), also a lefthand neighbour, unless it is the first element of the way.
Below is the code as requested
#include <windows.h>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <cstring>
#include <cstdint>
#include <cstdio>
#include <set>
#include <vector>
using namespace std;
set<string>PresentStreet;
set<int>PresentNode;
vector<string>NeighBours;
string line1;
void split(const string& s, char c,
vector<string>& v) {
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos) {
v.push_back(s.substr(i, j-i));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
v.push_back(s.substr(i, s.length()));
}
}
int main(int argc, char *argv[]) {
ifstream myfile ("filename.txt");
int CounterLine=1;
while ( getline (myfile,line1) ) {
string s1=line1;
vector<string> v1;
split(line1, ';', v1);
PresentStreet.insert(v1[2]);
vector<string> v2;
split(v1[4], ',', v2);
for (int t=0;t<v2.size();t++) {
auto search = PresentNode.find(atoi(v2[t].c_str()));
if(search == PresentNode.end()) {
string Neighbours="";
if(v1[3].find("no")!=std::string::npos&&t>0) {
Neighbours=Neighbours+v2[t-1]+",";
}
if(t<v2.size()-1) {
Neighbours=Neighbours+v2[t+1]+",";
}
stringstream ss;
ss<<CounterLine;
stringstream ss2;
ss2<<v2[t];
PresentNode.insert(atoi(v2[t].c_str()));
NeighBours.push_back(Neighbours);
}else{
int nPosition = distance (PresentNode.begin (), search);
string Neighbours=NeighBours[nPosition];
if(v1[3].find("no")!=std::string::npos&&t>0) {
Neighbours=Neighbours+v2[t-1]+",";
}
if(t<v2.size()-1) {
Neighbours=Neighbours+v2[t+1]+",";
}
NeighBours.at(nPosition)=Neighbours;
}
}CounterLine++;
}
}

Related

How to capitalize the first letter of each name in an array?

Here is the question:
Create a function that takes an array of names and returns an array where only the first letter of each name is capitalized.
example
capMe(["mavis", "senaida", "letty"]) âžž ["Mavis", "Senaida", "Letty"]
And the code I wrote to answer this question:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void capme(vector<string> name)
{
char ch;
for(int i = 0; i < name[i].size(); i++)
{
putchar(toupper(name[i][0]));
cout << name[i] << endl;
}
}
int main()
{
vector <string> name = {"mavis", "senaida", "letty"};
capme(name);
return 0;
}
As you can see, it prints "Mmavis", "Ssenaida", "Lletty", which is wrong. Can you guys help me in answering this question as I don't know how?
To change the input argument, we have two choice: make the argument mutable reference, or add a return type, here I choose the first one.
putchar can be used to print only one character, it recommended to use cout to print a string, possible solutions:
with traditional loop: capme
with range for-loop since c++11 : capme2
with stl algorithm transform: capme3
Don't forget to check if the string element is empty, or you may crash while accessing the first character.
To obey the single-responsibility principle (SRP), it's better to print the string vector out of the capme function.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void capme(vector<string>& name) {
for (int i = 0; i < name[i].size(); i++) {
if (name[i].empty()) continue;
name[i][0] = toupper(name[i][0]);
}
}
void capme2(vector<string>& names) {
for (auto& name : names) {
if (name.empty()) continue;
name[0] = toupper(name[0]);
}
}
void capme3(vector<string>& names) {
std::transform(names.begin(), names.end(), names.begin(), [](auto& s) {
return s.empty() ? s : (s[0] = toupper(s[0]), s);
});
}
Online demo
You have used the wrong function. What you need is a replacement and not a prepend. Try using std::string::operator[] to access the first element of the words in the vector. This is how I would write this code:
std::vector<string> capitaliseInitLetter(std::vector<string> vec) {
for (auto& word : vec) {
word[0] -= 32; //add a check to see if the letter is already capital
}
return vec;
}
The above code is just an example which assumes that the input is valid. You'll have to add checks and exception handling for invalid inputs on your own. (Hint: Take a look at #prehistoricpenguin's answer)
You are calling putchar() which writes a character to standard output, and in this case is printing the first letter of each string in name as uppercase, then you are writing the entire string to standard output immediately after.
Additionally, your function does not meet the requirements you stated above saying it should return an array where the strings have the first letter capitalized.
What you could do is change the signature of capme() to return a std::vector<std::string>, and perhaps utilize the for_each() function to handle changing the first letter of each string in your vector then return it.
For reference:
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
std::vector<std::string> capme(std::vector<std::string> name)
{
std::for_each(name.begin(), name.end(), [](std::string &s) {
s[0] = toupper(s[0]);
});
return name;
}
Or as kesarling suggested, a simple for each loop:
std::vector<std::string> capme(std::vector<std::string> name)
{
for (auto& s : name) {
s[0] = toupper(s[0]);
}
return name;
}

How to check if a string ends with 'ed' in C++;

How to write a program that reads 5 strings from user input and prints only those strings that end with the letter ‘ed’ in C++. Need help!
The solution is rather straightforward.
First we define a container that can contain 5 std::string. For that we use a std::vector together with a constructor to reserve space for the 5 elements.
Then we copy 5 strings from the console (from user input) into the vector.
And, last, we copy elements out of the std::vector to std::cout, if the strings end with "ed".
Because of the simplicity of the program, I cannot explain much more . . .
Please see.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
constexpr size_t NumberOfTexts = 5U;
int main()
{
// Define a container that can hold 5 strings
std::vector<std::string> text(NumberOfTexts);
// Read 5 strings from user
std::copy_n(std::istream_iterator<std::string>(std::cin), NumberOfTexts, text.begin());
// Print the strings with ending "ed" to display
std::copy_if(text.begin(), text.end(), std::ostream_iterator<std::string>(std::cout,"\n"), [](const std::string& s){
return s.size()>=2 && s.substr(s.size()-2) == "ed";
});
return 0;
}
Simple solution,
#include<iostream>
using namespace std;
bool endsWith(const std::string &mainStr, const std::string &toMatch)
{
if(mainStr.size() >= toMatch.size() &&
mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
return true;
else
return false;
}
int main()
{
string s[5];
for(int i=0;i<5;i++)
{
cin>>s[i];
}
for(int i=0;i<5;i++)
{
if(endsWith(s[i],"ed"))
cout<<s[i]<<endl;
}
}
Hope This might Helps:)

Insertion and Deletion in list <string>

I am currently writing a small program to insert or delete a row in a list of string read from an input text file.
This is my code
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
int main()
{
list <string> buffer;
string fileName = "input.txt";
ifstream file(fileName);
if (file.is_open())
{
string line;
while (getline(file, line))
{
//store each line in the buffer
buffer.push_back(line);
}
}
list<string>::const_iterator it;
it = buffer.begin();
int position = 1;
for (int n = 0; n < position; ++n)
{
++it;
}
string input("This is a new line");
buffer.insert(it, 1, input);
//I can then use erase function to delete a line
system("pause");
return 0;
}
The buffer list has
This is line 1
This is line 2
This is line 3
This is line 4
I want to know if there are other ways (maybe more efficient) to insert or delete a line in the buffer. Thank you!
There are several versions of list<>::insert(). One of them inserts a single element, so you can replace this:
buffer.insert(it, 1, input);
with:
buffer.insert(it, input);
You can also use list<>::emplace() to create the string in place :
buffer.emplace(it, "This is a new line");
You can simplify this:
list<string>::const_iterator it;
it = buffer.begin();
int position = 1;
for (int n = 0; n < position; ++n)
{
++it;
}
to:
auto it = buffer.begin();
advance(it, 1);

Atoi function while reading a .csv file C++

The execution of my code crashes when it gets to the "atoi" function, but I cannot understand why.
The code is supposed to read a matrix from a .csv file, considering:
- the first row (so till the first '\n') and saving each element (separated by a ',') in a vector of ints; - the rest of the matrix, by looking at each element and creating a specific object if the number read is 1 or 2.
I don't get any exception while debugging the program, it just crashes during the execution (and using the system ("PAUSE") I could figure out it was the atoi function which didn't work properly).
Can you help me understand what is going wrong?
Thank you very much.
Ps: I also attached all the libraries I'm loading... maybe it can help :)
#include <fstream>
#include <stdio.h>
#include <sstream>
#define nullptr 0
#include <string>
#include "classi.h"
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
ifstream file("problem.csv");
unsigned int N = 0;
unsigned int M = 0;
char c; //modificato char * c;
unsigned int i=0,j=0, k=0, n_iter, j_temp =0;
std::vector<car> v_row;
std::vector<car> v_col_temp;
std::vector<int> iter; // location where I want to save the ints corresponding to the elements of the first row of the .csv file //
std::string iterazioni; //location where I want to save the first row as a string and then cut it into pieces (iteraz) and then convert (atoi --> iter)
std::string iteraz;
while(!file.eof()){
std::getline(file,iterazioni,'\n');
stringstream it(iterazioni);
while (it.good()) {
std::getline(it,iteraz, ',');
iter[k] = atoi(iteraz.c_str());
if(iter[k]<0){
cout<<"Errore: negative #of iterations"<<endl;
break;
}
iter.push_back(0);
k++;
}
iter.pop_back();
file.get(c);
if (c=='1'){
blue_car b(i,j);
if (v_col_temp[i].get_next() != nullptr)
v_col_temp[i].insert_tail(&b);
else
v_col_temp[i].insert_head(&b);
}
if (c=='2'){
red_car r(i,j);
if (v_row[i].get_next() != nullptr)
v_row[i].insert_tail(&r);
else
v_row[i].insert_head(&r);
}
if (c==',') {
j++;
if (i == 0)
j_temp++;
}
if (c=='\n'){
car p;
v_row.push_back(p);
v_col_temp.push_back(p);
i++;
if (j != j_temp) {
std ::cout<<"errore input non valido: numero righe/colonne non coerente"<<endl;
}
j=0;
}
else if ((c!='\n') && (c!=',') && (c!='0') && (c!='1') && (c!='2'))
std ::cout<<"errore input non valido"<<endl;
};
n_iter = k-1;
M=i;
N=j+1;
...
Your program crashes because you failed to initialize the contents of the iter vector.
std::vector<int> iter; // location where I want to save the ints corresponding to the elements of the first row of the .csv file //
You declare and construct this vector. The vector is empty at this point, and it has no elements.
At some point later:
iter[k] = atoi(iteraz.c_str());
The initial value of k is 0, so this attempts to assign the return value from atoi() to iter[0].
The problem is, of course, there is no iter[0]. The iter vector is still empty, at this point.
Additional comments, which is sadly true for at least 50% of these kinds of questions on stackoverflow.com:
1) "using namespace std"; is a bad practice, that should be avoided
2) Do not use system("pause") as well, as you referenced in your question.

how to add an element to an array in c++?

How would I add an element to an array, assuming that I have enough space? My code looks something like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ofstream out("hi.out");
ifstream in("hi.in");
string currentLine;
string values[135];/*Enough for worst case scenario*/
if (out.is_open && in.isopen()){
while (in >> currentLine){
/*Add currentLine to values*/
}
/*Do stuff with values and write to hi.out*/
}
out.close()
in.close()
return 0;
}
No need to write the loop yourself. With your array:
auto l = std::copy(std::istream_iterator<std::string>(in), {}, values);
l - values is the number of strings read.
Or even better, use a vector, so that you don't have to worry about the possibility of your "worst case scenario" not being the actual worst case scenario.
std::vector<std::string> values(std::istream_iterator<std::string>(in), {});
You could use an index counter variable:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ofstream out("hi.out");
ifstream in("hi.in");
string currentLine;
string values[135];/*Enough for worst case scenario*/
int index = 0;
if (out.is_open && in.isopen()){
while (in >> currentLine){
/*Add currentLine to values*/
values[index++] = currentLine;
}
/*Do stuff with values and write to hi.out*/
}
out.close()
in.close()
return 0;
}
The variable index, once the loop is complete, will contain the number of strings in your array.