tags:

views:

1580

answers:

4

I want to fill these containers pretty quickly with some data for testing. What are the best and quick ways to do that? It shouldn't be too convoluted, and thus and inhumanly short, but also NOT to verbose

Edit

Guys I thought you can do something with memset knowning that vector has an underlining array? Also, what about map?

+5  A: 

You can use std::fill or std::generate.

Paul
examples please... :)
http://msdn.microsoft.com/en-us/library/kaxe2wy9.aspxhttp://msdn.microsoft.com/en-us/library/46h7chx6.aspx
Paul
+10  A: 
  • boost assignment library way (http://www.boost.org/doc/libs/1_38_0/libs/assign/doc/index.html)

    using namespace boost::assign;
    std::vector< int > v;
    v += 1,2,3,4,5,6,7,8,9;

    std::map< std::string, int > m;
    insert( m )( "Bar", 1 )( "Foo", 2 );

    vector< int > v;
    v += 1, 2, repeat_fun(4, &rand), 4;

  • std::generate or std::generate_n

  • std::backinserter - sometimes will help you
bb
+1  A: 

I use custom operators for inserting data:

#include <vector>
#include <iostream>
#include <string>

using namespace std;

template <class T>
vector<T>& operator<<(vector<T>& vec, const T& x) {
    vec.push_back(x);
    return vec;
}

vector<string>& operator<<(vector<string>& vec, char* cstr) {
    string s(cstr);
    vec.push_back(s);
    return vec;
}

int main() {
    vector<int> foo;
    vector<string> bar;
    foo << 7 << 8 << 9 << 10;
    bar << "foo" << "bar" << "baz";
}
argh, a simple for loop will do a more succinct job :)
+3  A: 

If you already have the initial data laying around, say in a C style array, don't forget that these STL containers have "2-iterator constructors".

const char raw_data[100] = { ... };

std::vector<char> v(raw_data, raw_data + 100);

Edit: I was asked to show an example for a map. It isn't often you have an array of pairs laying around, but in the past I have created a Python script that generated the array of pairs from a raw data file. I then #include this code-generated structure and initalized a map with it like this:

#include <map>
#include <string>
#include <utility>

using namespace std;

typedef map<string, int> MyMap;

// this array may have been generated from a script, for example:
const MyMap::value_type raw_data[2] = {
   MyMap::value_type("hello", 42),
   MyMap::value_type("world", 88),
};

MyMap my_map(raw_data, raw_data + 2);

Alternatively if you have an array of keys, and and array of data values, you can loop over them, calling map.insert(make_pair(key, value));

You also ask about memset and vector. I don't think there is any real merit to using memset to initialize a vector, because vectors can be given an initial value for all their elements via the constructor:

vector<int> v2(100, 42);  // 100 ints all with the value of 42
vector<string> v(42, "initial value");   // 42 copies of "initial value"
Brian Neal
now, how about map?
Added an example for map.
Brian Neal