logo
down
shadow

C++ vector.push_back adds objects twice when adding an object once


C++ vector.push_back adds objects twice when adding an object once

By : Tanvi Nishchal
Date : November 18 2020, 11:13 AM
I wish this help you There is nothing in the code shown that would make objects be inserted twice, so it comes down to some old-fashioned debugging skills. For a start, change the loader function to be something like:
code :
bool Level1::LoadContent() {
    std::cout << "Enter LoadContent with size " << SpriteList2.size() << '\n';

    Sprite1 Sprite_1({0.0f, 0.0f, 3.0f});//Define Sprite Object
    SpriteList2.push_back(Sprite_1);//Add Sprite Object to Vector

    Sprite1 Sprite_2({ 100.0f, 00.0f, 2.0f });//Define Sprite Object
    SpriteList2.push_back(Sprite_2);//Add Sprite Object to Vector

    Sprite1 Sprite_3({ 100.0f, -50.0f, 1.0f });//Define Sprite Object
    SpriteList2.push_back(Sprite_3);//Add Sprite Object to Vector

    std::cout << "Exit  LoadContent with size " << SpriteList2.size() << '\n';

    return true;
}
Enter LoadContent with size 0
Exit  LoadContent with size 6


Share : facebook icon twitter icon
Adding object to vector with push_back working fine, but adding objects with accessor syntax [ ] , not working

Adding object to vector with push_back working fine, but adding objects with accessor syntax [ ] , not working


By : user5903223
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You can't add new objects to vector using operator[]. .reserve() doesn't add them neither. You have to either use .resize() or .push_back().
Also, you are not avoiding overheads at all; call cost of operator[] isn't really much better that push_back() one, so until you profile your code thorougly, just use push_back. You can still use reserve to make sure unneccessary allocations won't be made.
C++ push_back only adds objects to position 0 in vector

C++ push_back only adds objects to position 0 in vector


By : Jo He
Date : March 29 2020, 07:55 AM
hope this fix your issue The issue is in your debugging.
This code adds a single, then expects three.
code :
void addResult(string type, string name, vector<Result *> results, double costs){
    results.push_back(new Result(type, name, costs));
    cout << results.at(0)->getName() << endl;
    cout << results.at(1)->getName() << endl;
    cout << results.at(2)->getName() << endl;
}
void getCosts(vector<Parts *> p){
    for(std::vector<Part *>::iterator ip = p.begin; ip != p.end(); ip++){
        addResult((*ip)->getType(), (*ip)->getName(), r, (*ip)->getPrice());
    }
    //Check results here.
}
void addResult(string type, string name, vector<Result *>& results, double costs)
C++ Vector: push_back Objects vs push_back Pointers performance

C++ Vector: push_back Objects vs push_back Pointers performance


By : PsychoticDuck
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , To be fair, when measuring your code you should account for deallocation of all those pointers. A sample code would read as :
code :
#include <chrono>
#include <string>
#include <iostream>
#include <functional>
#include <vector>

using namespace std;

// 1. A way to easily measure elapsed time -------------------
template<typename TimeT = std::chrono::milliseconds>
struct measure
{
    template<typename F>
    static typename TimeT::rep execution(F const &func)
    {
        auto start = std::chrono::system_clock::now();
        func();
        auto duration = std::chrono::duration_cast< TimeT>(
            std::chrono::system_clock::now() - start);
        return duration.count();
    }
};
// -----------------------------------------------------------


// 2. MyObject -----------------------------------------------
struct MyObject {
    string mem;
    MyObject(const char *text) : mem(text) {};
};
// -----------------------------------------------------------


int main() 
{
    vector<MyObject> VectorOfObjects;
    vector<MyObject *> VectorOfPointers;

    cout << "Pushback Object: " << measure<>::execution([&]()
    {
        for (int i = 0; i < 100000; i++) {
            MyObject x("test");
            VectorOfObjects.push_back(x);
        }
    }) << endl;


    cout << "Pushback Pointers: " << measure<>::execution([&]()
    {
        for (int i = 0; i < 100000; i++) 
            VectorOfPointers.push_back(new MyObject("test"));
        for (auto &item : VectorOfPointers) 
            delete item;
    }) << endl;

    return 0;
}
vector<MyObject> VectorOfObjects;
VectorOfObjects.reserve(100000);

vector<MyObject *> VectorOfPointers;
VectorOfPointers.reserve(100000);
vector<unique_ptr<MyObject>> VectorOfPointers;
Vector.push_back() adds same Element while reading from File

Vector.push_back() adds same Element while reading from File


By : taguchi
Date : March 29 2020, 07:55 AM
like below fixes the issue As mentioned in the comments, you are pushing the pointers back not the actual strings. To get the actual strings you can do this:
code :
void readFileToVec()
{
    ifstream file;
    file.open ("rb");
    vector<string> v;
    string word;
    while (file >> word)
    {
        v.push_back(word);
    }
}
Why can't I push_back an object into a vector of objects that belongs to another class?

Why can't I push_back an object into a vector of objects that belongs to another class?


By : Anwar
Date : March 29 2020, 07:55 AM
wish helps you RegLogBook::getVoterList() returns your _voterList by value. That means it copies the whole vector and returns it. Then you add elements to that copy.
To fix this, simply change your
code :
vector<Voter*> RegLogBook::getVoterList()
vector<Voter*>& RegLogBook::getVoterList()
//            ^ notice the reference part
void Committee::RegVoter(RegLogBook logs)
void Committee::RegVoter(RegLogBook& logs)
//      again notice the reference ^
Related Posts Related Posts :
  • Vector of pointers: some clarification needed
  • scaling a bitmap without losing quality
  • How to evaluate a function directly?
  • QNetworkAccessManager: How to change post data at createRequest function
  • Returning std::move of a local variable
  • Is there a fast linear SVM library with a good C++ interface?
  • What is the purpose of name mangling in C++?
  • C++ Why the void function is not working eventhough I called it?
  • How the pointer and the pointer's adress can share the same memory adress?
  • error C2220: warning treated as error - no 'object' file generated
  • exception of strcpy function in c++ console program
  • How to access USB barcode scanner data directly from USB port using C/C++ without driver
  • Under which circumstances will std::vector.clear() call a destructor?
  • Template partial specialisation and dependent names
  • best way to share data between c codes
  • C++ ignores if statement conditions
  • How to set the argv[ ] to be case-insensitive in a Win32 Console Application?
  • How to fix error "clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)"?
  • C++ How do I print a .txt file verbatim?
  • Creating two dimensional array of class
  • How do I correctly use COMMTIMEOUTS with OVERLAPPED IO mode reading from a Serial port
  • An assert macro which expands to static_assert when possible?
  • How to write a copyconstructor for a class which has HANDLE as a member in win32 c++ application?
  • C++ saving info such as tree in a file
  • Transforming an expression template tree
  • How to overload an operator with multiple parameters like a + b + c?
  • C++ 11 with Raspberry Pi performances
  • Make a C++ class look like a numpy array using swig
  • Postfix incrementer overloading for nested enumerated types
  • Is there a tidy way of associating metadata with functions in C++
  • QObject::installEventFilter(): Cannot filter events for objects in a different thread
  • LNK2005 error with Zxing C++
  • C++ Doubly Linked List with Pointers: Object of class isn't constructed properly
  • Using a random string generator in c++ constructor
  • What should I use instead of void as one of the alternative types in an variant?
  • C++ return value from multithreads using reference
  • How to connect multiple TCP IP clients to same server port using c++
  • Defaul compiler generates the reference operator (In C++)?
  • Unable to change directory time stamp after using FILE_FLAG_BACKUP_SEMANTICS
  • vector handling displaying output
  • WSAGetLastError returns WSAENOTSOCK - Cause?
  • C++: How to overload pow for user type?
  • C++ using arrays as multidimensional despite initalising it as 1D with pointer
  • How negate std::is_integral for use in tag dispatch?
  • Retrieve serial number from USB memory (Windows environment c++)
  • g++ error: invalid preprocessing directive #INCLUDE
  • C++ What is the std::for_each() function parameter type?
  • C++: Read individual lines from text file, sort words alphabetically
  • Saving 'this' address into a variable
  • c++ command line arguments in ubuntu terminal
  • Convert "Cartesian coordinates" to "polar coordinates with respect to user specified origin"
  • In what order are local scoped objects destructed?
  • How to use SDL_MapRGB with SDL 2.0
  • how compiler and interpreter work in case of array declaration
  • GSL integration behaves strange
  • Cropping an image with OpenCV and C
  • Find the last line in text file and select the first 10 char and print to a new file?
  • Created many CCSprits but when triggering ccTouchBegan gives the last one allways
  • seekp and seekg don't work with fstream
  • Taking input in Sublime Text 3
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org