के बारे में क्या:
#include <algorithm>
#include <boost/lexical_cast.hpp>
template<typename C1, typename C2>
void castContainer(const C1& source, C2& destination)
{
typedef typename C1::value_type source_type;
typedef typename C2::value_type destination_type;
destination.resize(source.size());
std::transform(source.begin(), source.end(), destination.begin(), boost::lexical_cast<destination_type, source_type>);
}
यह वेक्टर में बदल सकते हैं
std::transform(DataNumbers.begin(), DataNumbers.end(), std::back_inserter(Data),
[](const std::string& str) { return std::stoi(str); });
और यहाँ lambdas (बजाय std::bind
का प्रयोग करके) के बिना एक संस्करण है < स्ट्रिंग> वेक्टर < int>, और अन्य कंटेनर < टी 1> कंटेनरटी 2>, उदाहरण: सूची -> सूची में।
पूर्ण कोड:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <boost/lexical_cast.hpp>
template<typename C1, typename C2>
void castContainer(const C1& source, C2& destination)
{
typedef typename C1::value_type source_type;
typedef typename C2::value_type destination_type;
destination.resize(source.size());
std::transform(source.begin(), source.end(), destination.begin(), boost::lexical_cast<destination_type, source_type>);
}
template<typename T, typename T2>
std::vector<T>& operator<<(std::vector<T>& v, T2 t)
{
v.push_back(T(t));
return v;
}
main(int argc, char *argv[])
{
std::vector<std::string> v1;
v1 << "11" << "22" << "33" << "44";
std::cout << "vector<string>: ";
std::copy(v1.begin(), v1.end(), std::ostream_iterator<std::string>(std::cout, ", "));
std::cout << std::endl;
std::vector<int> v2;
castContainer(v1, v2);
std::cout << "vector<int>: ";
std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
}
स्रोत
2013-09-14 09:27:16
वास्तव में क्या अपने लक्ष्य को यहाँ है? संख्या में कौन से प्रारूप हैं? प्रदर्शन बनाम पठनीयता कितना महत्वपूर्ण है? –
मुझे केवल पूरी संख्या की आवश्यकता है। और उसके बाद मैं इस int वेक्टर –