Модераторы: Daevaorn
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> <map.h> kak добавить элемент в map container 
:(
    Опции темы
brockel
  Дата 7.10.2006, 14:53 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 22
Регистрация: 21.9.2006

Репутация: нет
Всего: нет



typedef map<string, Tag::Value, less<string> > Map;
Map attributes;

attributes //сюда хочу положитьь новый элемент.
PM MAIL   Вверх
Daevaorn
Дата 7.10.2006, 15:30 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Комодератор
Сообщений: 2155
Регистрация: 29.11.2004
Где: Москва

Репутация: 51
Всего: 70



brockel,
Код

attributes[ "key" ] = value;


PM MAIL WWW   Вверх
Damarus
Дата 7.10.2006, 15:33 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Awaiting Authorisation
Сообщений: 671
Регистрация: 6.5.2006

Репутация: 6
Всего: 29



map::insert
Код
// map_insert.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( ) {
   using namespace std;
   map <int, int>::iterator m1_pIter, m2_pIter;

   map <int, int> m1, m2;
   typedef pair <int, int> Int_Pair;

   m1.insert ( Int_Pair ( 1, 10 ) );
   m1.insert ( Int_Pair ( 2, 20 ) );
   m1.insert ( Int_Pair ( 3, 30 ) );
   m1.insert ( Int_Pair ( 4, 40 ) );

   cout << "The original key values of m1 =";
   for ( m1_pIter = m1.begin( ); m1_pIter != m1.end( ); m1_pIter++ )
      cout << " " << m1_pIter -> first;
   cout << "." << endl;

   cout << "The original mapped values of m1 =";
   for ( m1_pIter = m1.begin( ); m1_pIter != m1.end( ); m1_pIter++ )
      cout << " " << m1_pIter -> second;
   cout << "." << endl;

   pair< map<int,int>::iterator, bool > pr;
   pr = m1.insert ( Int_Pair ( 1, 10 ) );

   if( pr.second == true ) {
      cout << "The element 10 was inserted in m1 successfully." << endl;
   }
   else {
      cout << "Key number 1 already exists in m1\n"
           << "with an associated value of ( (pr.first) -> second ) = " 
           << ( pr.first ) -> second 
           << "." << endl;
   }

   // The hint version of insert
   m1.insert( --m1.end( ), Int_Pair ( 5, 50 ) );

   cout << "After the insertions, the key values of m1 =";
   for ( m1_pIter = m1.begin( ); m1_pIter != m1.end( ); m1_pIter++ )
      cout << " " << m1_pIter -> first;
   cout << "," << endl;

   cout << "and the mapped values of m1 =";
   for ( m1_pIter = m1.begin( ); m1_pIter != m1.end( ); m1_pIter++ )
      cout << " " << m1_pIter -> second;
   cout << "." << endl;

   m2.insert ( Int_Pair ( 10, 100 ) );

   // The templatized version inserting a range
   m2.insert( ++m1.begin( ), --m1.end( ) );

   cout << "After the insertions, the key values of m2 =";
   for ( m2_pIter = m2.begin( ); m2_pIter != m2.end( ); m2_pIter++ )
      cout << " " << m2_pIter -> first;
   cout << "," << endl;

   cout << "and the mapped values of m2 =";
   for ( m2_pIter = m2.begin( ); m2_pIter != m2.end( ); m2_pIter++ )
      cout << " " << m2_pIter -> second;
   cout << "." << endl;
}


map::operator[] 
Код
// map_op_insert.cpp
// compile with: /EHsc
#include <map>
#include <iostream>

int main( )
{
   using namespace std;
   typedef pair <const int, int> cInt2Int;
   map <int, int> m1;
   map <int, int> :: iterator pIter;
   
   // Insert a data value of 10 with a key of 1
   // into a map using the operator[] member function
   m1[ 1 ] = 10;

   // Compare other ways to insert objects into a map
   m1.insert ( map <int, int> :: value_type ( 2, 20 ) );
   m1.insert ( cInt2Int ( 3, 30 ) );

   cout  << "The keys of the mapped elements are:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> first;
   cout << "." << endl;

   cout  << "The values of the mapped elements are:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> second;
   cout << "." << endl;

   // If the key already exists, operator[]
   // changes the value of the datum in the element
   m1[ 2 ] = 40;

   // operator[] will also insert the value of the data
   // type's default constructor if the value is unspecified
   m1[5];

   cout  << "The keys of the mapped elements are now:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> first;
   cout << "." << endl;

   cout  << "The values of the mapped elements are now:";
   for ( pIter = m1.begin( ) ; pIter != m1.end( ) ; pIter++ )
      cout << " " << pIter -> second;
   cout << "." << endl;
}


PM MAIL ICQ Jabber   Вверх
Daevaorn
Дата 7.10.2006, 15:34 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Комодератор
Сообщений: 2155
Регистрация: 29.11.2004
Где: Москва

Репутация: 51
Всего: 70



Или
Код

typedef pair< string, Tag::Value > Pair;
attributes.insert( Pair( key, value ) );

PM MAIL WWW   Вверх
Мяут
Дата 9.10.2006, 18:11 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











Код

template <class Map, typename Key, typename Value>
void doinsert(Map& m, Key key, Value val) {    
 m.insert(std::pair<Key, Value>(key,val));
}


Зато оригинально  smile 
  Вверх
JackYF
Дата 9.10.2006, 18:20 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


полуавантюрист
****


Профиль
Группа: Участник
Сообщений: 5814
Регистрация: 28.8.2004
Где: страна тысячи озё р

Репутация: 18
Всего: 162



Мяут, твой пример можно было бы немного изменить.. так, например:

Код

template <typename Key, typename Value, typename GreaterLess>
void doinsert( std::map< Key, Value, GreaterLess >& m, const Key& key, const Value& val )
{    
   m.insert(std::pair<Key, Value>(key,val));
}

template <typename Key, typename Value, typename GreaterLess>
void doinsert( std::multimap< Key, Value, GreaterLess >& m, const Key& key, const Value& val )
{    
   m.insert(std::pair<Key, Value>(key,val));
}


Так, по-моему, больше потенциальных ошибок отсекается... ИМХО.

Добавлено @ 18:21 
Да и функцию назвать как-нибудь типа doMapInsert, что ли...  smile 


--------------------
Пожаловаться на меня как модератора можно здесь.
PM MAIL Jabber   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "С++:Общие вопросы"
Earnest Daevaorn

Добро пожаловать!

  • Черновик стандарта C++ (за октябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика(4.4мб).
  • Черновик стандарта C (за сентябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика (3.4мб).
  • Прежде чем задать вопрос, прочтите это и/или это!
  • Здесь хранится весь мировой запас ссылок на документы, связанные с C++ :)
  • Не брезгуйте пользоваться тегами [code=cpp][/code].
  • Пожалуйста, не просите написать за вас программы в этом разделе - для этого существует "Центр Помощи".
  • C++ FAQ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Earnest Daevaorn

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0452 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.